命名URL和反向解析
在网页中某些要提交的地址等,需要改变的时候,此时网页过多,如果一个一个的去改,工作量巨大,这时就可以用到命名url,在html文件的模版中,只写命名,这样当需要我们改变urls.py中的url映射的网页地址时,就方便多了
1.普通的URL
urls.py
from django.conf.urls import url
from app01 import views
urlpatterns = [
url(r'^blog/', views.blog, name='xxx')
]
# name='xxx'是url的命名
url的命名使用:
? 1.视图函数
2.html网页的模版中
1.视图函数
views.py
from django.shortcuts import render, HttpResponse, redirect, reverse
def blog(request):
url = reverse('xxx')
print(url)
return HttpResponse('blog')
这时,我们访问地址就可以得到反向的url,views.py中的函数改为
def blog(request):
return redirect(reverse('xxx')) # ----> /app01/blog [blog就是xxx找到的]
2.模版中使用
语法:
{% url 名字%}
示例:
<a href="{% url 'xxx' %}">url命名和反向解析</a>
二.使用分组的形式
1.视图函数中应用
urls.py
from django.conf.urls import url
from app01 import views
urlpatterns = [
??url(r'^home/', views.home, name='home'),
??url(r'^blog/(\d{4})/([1-9]{2})', views.blog, name='xxx'),
]
veiws.py
from django.shortcuts import render, HttpResponse, redirect, reverse
def blog(request,y,m):
??url = reverse('xxx')
??print(url)
??return redirect(reverse('xxx'))
??
def home(request):
??url = reverse('xxx',args=('2018','12'))
??print('home的url',url) ?????????????# /blog/2018/12
??return HttpResponse('HOME页面')
这时候你访问 http://127.0.0.1:8000/home/ 就会得到 home的url /blog/2018/12
2.模版中使用
{% url 'xxx' 参数%}
三.使用命名分组
1.视图函数中的应用
urls.py
from django.conf.urls import url
from app01 import views
urlpatterns = [
??url(r'^home/', views.home, name='home'),
??# url(r'^blog/(\d{4})/([1-9]{2})', views.blog, name='xxx'),
??url(r'^blog/(?P<year>\d{4})/(?P<month>[1-9]{2})', views.blog, name='xxx'),
]
views.py
from django.shortcuts import render, HttpResponse, redirect, reverse
def blog(request,y,m):
??url = reverse('xxx')
??print(url)
??return redirect(reverse('xxx'))
def home(request):
??# url = reverse('xxx',args=('2018','12'))
??# print('home的url',url) # 也可以使用
?
??url = reverse('xxx', kwargs={'year':'2018','month':'12'})
??print('home的命名的url', url)
?
??return HttpResponse('HOME页面')
2.模版中使用
示例:
{% url 'del_pub' year='2018' month='12' %} ???// del_pub别名
原文地址:https://www.cnblogs.com/robertx/p/10427133.html
时间: 2024-10-09 23:13:11