Django---URL

    • Django的URL配置
      • 1 静态路由
      • 2 动态路由
        • 位置参数
        • 关键字参数
      • 3 路由分发
      • 4 向view函数中传参
      • 5 向include中传参
      • 6 URL别名

1. Django的URL配置

1.1 静态路由

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^hello/$', hello),
    url(r'^time/$', current_datetime),
]

^time/$这样的url是固定了,也就是静态的,请求时只能以这种格式

1.2 动态路由

位置参数

  • 设置位置参数
urlpatterns = [
    # ...
    url(r'^time/plus/(\d+)/(\d+)/$', hours_ahead),
    # ...
]

^time/plus/(\d+)/$这样可以匹配以time/plus/开头后接一组数字的结尾的URL成为动态路由。
动态路由的关键是使用正则表达式,需要注意的是正则表达式必须包含在圆括号中

  • 接收位置参数
    在views中定义的函数中添加参数来获取

    def hours_ahead(request, a1, a2):
      try:
          a1 = int(a1)
          a2 = int(a2)
      except ValueError:
          raise Http404()
    
      html = "The first one is %s, and the second one is %s" % (a1, a2)
      return HttpResponse(html)

    以URLhttp://127.0.0.1:8000/time/plus/22/33/为例,可以看出第一个参数a1接收URL中的22,第二个参数a2接收URL中的33。打印结果The first one is 22, and the second one is 33
    如果将参数中的a1a2的位置调换,那么a1a2的值结汇调换。打印结果The first one is 33, and the second one is 22

关键字参数

  • 设置关键字参数
    通过?P作为正则表达式的前缀实现关键字参数设置,其中arg为参数的名称,在views中设置视图函数要使用。具体用例如下所示。

    urlpatterns = [
      ...
      url(r'^time/plus/(?P\d+)/(?P\d+)/$', views.hours_ahead),
    ...
    
    ]
  • 接收关键字参数
    视图函数如下所示:

    def hours_ahead(request, a1, a2):
      try:
          a1 = int(a1)
          a2 = int(a2)
      except ValueError:
          raise Http404()
    
      html = "The first one is %s, and the second one is %s" % (a1, a2)
      return HttpResponse(html)

    http://127.0.0.1:8000/time/plus/22/33/为例,虽然函数参a1的位置在a2之前,但a1接收33a2接收22,按照URL中的顺序接收。
    打印结果如下所示
    The first one is 33, and the second one is 22

1.3 路由分发

from django.conf.urls import include, url
from apps.main import views as main_views
from credit import views as credit_views
extra_patterns = [
    url(r'^reports/(?P[0-9]+)/$', credit_views.report),
    url(r'^charge/$', credit_views.charge),
]
urlpatterns = [
    url(r'^$', main_views.homepage),
    url(r'^help/', include('apps.help.urls')), # 包含其他URL文件
    url(r'^credit/', include(extra_patterns)), # 当前文件URL分组
]

使用URL分组的方法使得URL更加简洁,

不分组的URL

from django.conf.urls import url
from . import views
urlpatterns = [
    url(r'^(?P\w+)-(?P\w+)/history/$',views.history),
    url(r'^(?P\w+)-(?P\w+)/edit/$', views.edit),
    url(r'^(?P\w+)-(?P\w+)/discuss/$', views.discuss),
    url(r'^(?P\w+)-(?P\w+)/permissions/$',views.permissions),
]

使用URL分组

from django.conf.urls import include, url
from . import views
extra_patterns = [
    url(r'^history/$', views.history),
    url(r'^edit/$', views.edit),
    url(r'^discuss/$', views.discuss),
    url(r'^permissions/$', views.permissions),
]

urlpatterns = [
    url(r'^(?P\w+)-(?P\w+)/', include(extra_patterns)),
]

如果只分一组,为了不新命名一个组可以使用如下方式

urlpatterns = [
    url(r'^(?P\w+)-(?P\w+)/', include(
        [
            url(r'^history/$', views.history),
            url(r'^edit/$', views.edit),
            url(r'^discuss/$', views.discuss),
            url(r'^permissions/$', views.permissions),
        ]
    )),
]

通过分组减少了重复代码的书写,也减少了输入错误。

1.4 向view函数中传参

url中有三个参数,一般我们适用前两个,分别是匹配URL的正则表达式和与之对应的views函数,此外还有第三个参数,用来向views函数中传递参数。第三个参数的格式为字典格式,如下所示。

from django.conf.urls import url
from . import views
urlpatterns = [
    url(
        r'^reviews/(?P[0-9]{4})/$',
        views.year_archive,
        {'foo': 'bar'}
       ),
]

如果发送一个/reviews/2005/ 的请求,Django会调用函数

views.year_archive(request,year='2005',foo='bar')

1.5 向include中传参

向include中传参,就是对include中包含的每一个URL传相同的参数

# main.py
from django.conf.urls import include, url
urlpatterns = [
    url(r'^reviews/', include('inner'), {'reviewid': 3}),
]
# inner.py
from django.conf.urls import url
from mysite import views
urlpatterns = [
   url(r'^archive/$', views.archive),
   url(r'^about/$', views.about),
]

这种方式和下面的方式是等价的

# main.py
from django.conf.urls import include, url
from mysite import views
urlpatterns = [
    url(r'^reviews/', include('inner')),
]
# inner.py
from django.conf.urls import url
urlpatterns = [
    url(r'^archive/$', views.archive, {'reviewid': 3}),
    url(r'^about/$', views.about, {'reviewid': 3}),
]

1.6 URL别名

from django.conf.urls import url
from . import views
urlpatterns = [
#...
url(r'^reviews/([0-9]{4})/$', views.year_archive, name='reviews-year-archive'),
#...
]
<a href="{% url 'reviews-year-archive' 2012 %}">2012 Archivea>
{# Or with the year in a template context variable: #}
<ul>
    {% for yearvar in year_list %}
        <li><a href="{% url 'reviews-year-archive' yearvar %}">{{ yearvar }}Archivea>li>
    {% endfor %}
ul>
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
def redirect_to_year(request):
    # ...
    year = 2012
    # ...
    return HttpResponseRedirect(reverse('reviews-year-archive', args=(year,)))

你可能感兴趣的:(django)