django-URL别名的作用(六)

前端之家收集整理的这篇文章主要介绍了django-URL别名的作用(六)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

接include函数那一节。

作用:为URL地址取一个名称,这样在html中引用的时候,无论后台url怎么变,都可以访问到对应的界面,可以减少更改的次数

基本目录:

 

 book\urls.py

  1. from django.urls import path
  2. from . views
  3. urlpatterns = [
  4. path('',views.index,name='index'),path(news/',views.news,1)">newsvideos/videos
  5. from django.shortcuts  render
  6. from django.http  HttpResponse
  7. # Create your views here.
  8. def index(request):
  9.     return render(request,index.html)
  10.  news(request):
  11.     return HttpResponse(我是新闻的首页页面 videos(request):
  12.     我是视频的首页页面')

book\templates\index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <Meta charset=UTF-8">
  5. <title>Title</title>
  6. <style>
  7. p{font-size: 28px;}
  8. </style>
  9. </head>
  10. <body>
  11. <p><a href={% url '%}>index</a></p>
  12. <p><a href={% url '%}>news</a></p>
  13. <p><a href={% url '%}>videos</a></p>
  14. </body>
  15. </html>

当我们启动服务器后,会首先调用book\views.py中的index函数跳转到index.html

 

 点击news

 

 点击videos

 

 如果我们不取名字,那么在html中要用"http://localhost:8000/videos",这样虽然也有相同的作用,但是更改urls里面的path后,这里的同样也要更改,较为繁琐。

 

猜你在找的Django相关文章