url配置:
from django.conf.urls import url from . import views urlpatterns = [ url(r'^articles/2003/$', views.special_case_2003), url(r'^articles/([0-9]{4})/$', views.year_archive), url(r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive), url(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', views.article_detail), ]
上面最后一个url将调用views.article_detail(request, '2003', '03', '03'),函数参数按顺序来,如果想对参数命名可以采用下面的方式:
from django.conf.urls import url from . import views urlpatterns = [ url(r'^articles/2003/$', views.special_case_2003), url(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive), url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive), url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})/$', views.article_detail), ]
这个时候会调用views.article_detail(request, year='2003', month='03', day='03'),更加明晰且不容易产生参数顺序问题的错误
# URL 的反向解析,在需要URL 的地方,对于不同层级,Django 提供不同的工具用于URL 反查: from django.conf.urls import url urlpatterns = [ url(r'^articles/([0-9]{4})/$', views.year_archive, name='news-year-archive'), ] #1.在模板中使用url模板标签。例:<a href="{% url 'news-year-archive' 2012 %}">2012 Archive</a> #2.在Python 代码中:使用django.core.urlresolvers.reverse() 函数。 在Python 代码中,这样使用: from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect def redirect_to_year(request): ... year = *** return HttpResponseRedirect(reverse('news-year-archive', args=(year,))) #3.在处理Django 模型实例相关的代码中:使用get_absolute_url() 方法。 class ModelName(models.Model): ... def get_absolute_url(self): from django.core.urlresolvers import reverse return reverse('people.views.details', args=[str(self.id)]) # 在模板中这样使用,相对于给模型中的每个实例绑定了一个url属性: <a href="{{ object.get_absolute_url }}">{{ object.name }}</a> # urls中的参数 #直接第一个匹配的传递给nid,第二个匹配的传递给uid,这样和views里的函数形参位置没有关系了。 urls.py:url(r'^detail-(?P<nid>d+)-(?P<uid>d+).html/', views.detail), views.py:def detail(request, nid, uid): #访问网址:127.0.0.1/detail-key1-9.html #分组时,个数不确定*args,**kwargs也能使用 url(r'^detail-(keyd+)-(d+).html/', views.detail), ——> def detail(request, *args): url(r'^detail-(?P<nid>d+)-(?P<uid>d+).html/', views.detail), ——> def detail(request, **kwargs):