Django's routing system: URL

A, URLconf configuration

  1. The basic format

    from django.conf.urls import url
    urlpatterns = [
         url(正则表达式, views视图,参数,别名),
    ]
    • Parameter Description
      • Regular Expressions: A regular expression string
      • views view: a callable object, a view is generally a function of
      • Parameters: The optional parameters to be passed to the default view function (a dictionary)
      • Alias: An optional parameter name
  2. django 2.0 version of the routing system

    • Re_path version 2.0 and version 1.11 of the url is the same usage
    from django.urls import path,re_path
    urlpatterns = [
        path('articles/2003/', views.special_case_2003),
    ]

Second, the regular expression

  1. basic configuration

    from django.conf.urls import url
    from . import views
    urlpatterns = [
        url(r'^articles/2003/$', views.special_case_2003),
    ]
  2. Precautions

    • urlpatterns the elements one by one in the writing order to match the regular expression from the top down, will not continue once the match is successful
    • To capture a value from the URL, only to place a pair of parentheses around it (using the packet match)
    • No need to add a leading backslash, because each URL has. For example, it should be ^ articles, not ^ / articles
    • Each regular expression in front of the 'r' is optional, but suggested adding
  3. Supplement

    • Whether open access URL address is not behind / jump to the path with / of configuration items: APPEND_SLASH = True
    • Django settings.py file in the default configuration does not APPEND_SLASH this parameter, but Django default this parameter is APPEND_SLASH = True, its role is automatically added to the end of the URL '/'

Third, the group name to match

  1. Group: simple regular expression matching packet (by the parentheses) to capture the value of the URL and passed as parameters to the position of the view function

    from django.conf.urls import url
    from . import views
    urlpatterns = [
        url(r'^articles/([0-9]{4})/$', views.year_archive),
        url(r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive),
    ]
  2. Naming packet: packet using regular expression matching name set to capture the value of the URL and passed as parameters to the view of the function key

    from django.conf.urls import url
    from . import views
    urlpatterns = [
        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),
    ]
    • Added: When the third parameter url of a dictionary representing additional keyword arguments you want to pass to the view function
      • When the dictionary to pass additional parameters in the URL parameters and capture the value of the named keyword arguments of the same name, the function is called, it will use a dictionary of parameters, rather than captured parameters in the URL
      • That is the priority: Additional parameters> URL capture parameters
  3. UPLconf match Location:

    • URLconf look at the URL request, it will be treated as a normal Python string, not including GET and POST parameters, and domain name
      • http://www.example.com/myapp/Request, URLconf will look for / myapp /
      • http://www.example.com/myapp/?page=3Request, URLconf will look for / myapp /
    • URLconf request method does not check, i.e., all requests method (with one URL POST, GET, HEAD, etc.), are routed to the same function
  4. Capturing parameters are strings: each captured in a URLconf parameters as a normal Python string to view function, regardless of regular expressions to match what way

  5. There are individual cases, need to specify a default value view function

    # urls.py中
    from django.conf.urls import url
    from . import views
    urlpatterns = [
        url(r'^blog/$', views.page),
        url(r'^blog/page(?P<num>[0-9]+)/$', views.page),
    ]
    # 两个URL模式指向相同的view,但是第一个模式并没有从URL中捕获任何东西
    
    # views.py中,可以为num指定默认值
    def page(request, num="1"):
        pass
    # 如果第一个模式匹配上了,page函数将使用其默认参数num=“1”,如果第二个模式匹配,page将使用正则表达式捕获到的num值
  6. include: route distribution

    • According to different functions or types, you can put different routing functions written in the function of the app file, include the use of linked url equivalent to the different functions in different space
    from django.conf.urls import include, url
    urlpatterns = [
       url(r'^admin/', admin.site.urls),
       url(r'^app01/', include('app01.urls')),  # 可以包含其他的URLconfs文件
    ]
    • Supplementary: app01.urls
    from django.conf.urls import url
    from . import views
    urlpatterns = [
        url(r'^blog/$', views.blog),
        url(r'^blog/(?P<year>[0-9]{4})/(?P<month>\d{2})/$', views.blogs),
    ]
    • include a namespace parameters: namespace
      • Easy to distinguish different routing functions with the same name present in the space, to facilitate exact function specified
    from django.conf.urls import include, url
    urlpatterns = [
        url(r'^app01/', include('app01.urls', namespace='app01')),
        url(r'^app02/', include('app02.urls', namespace='app02')),
    ]

Fourth, the name and URL of the reverse analysis

4.1 URL name

  1. Url fourth parameter is an alias, i.e. an optional parameter name

  2. Named: name = 'alias'

    from django.conf.urls import url
    urlpatterns = [
     url(r'^home', views.home, name='home'),        # 给我的url匹配模式起名为 home
     url(r'^index/(\d*)', views.index, name='index'),       # 给我的url匹配模式起名为index
    ]

4.2 reverse lookup

  1. Reverse resolution: get the full URL path alias

  2. Case 1: Static Routing

    • name
    from django.conf.urls import url
    urlpatterns = [
     url(r'^blog/$', views.blog, name='blog'),
    ]
    • Used in the template
    {% url 'blog' %}         {# 完整URL路径:/blog/ #}
    • py file in use
    from django.urls import reverse
    reverse('blog')           # 完整URL路径:/blog/
  3. Scenario 2: Grouping

    • name
    from django.conf.urls import url
    urlpatterns = [
     url(r'^blog/([0-9]{4})/(\d{2})/$', views.blogs, name='blogs'),
    ]
    • Used in the template
    {% url 'blogs' 2222 12 %}        {# 完整URL路径:/blog/2222/12/ #}
    • py file in use
    from django.urls import reverse
    reverse('blogs',args=('2019','06'))        # 完整URL路径:/blog/2019/06/ 
  4. Case three: group name

    • name
    from django.conf.urls import url
    urlpatterns = [
     url(r'^blog/(?P<year>[0-9]{4})/(?P<month>\d{2})$', views.blogs, name='blogs'),
    ]
    • Used in the template
    {% url 'blogs' year=2222 month=12 %}      {# 完整URL路径:/blog/2222/12/ #}
    • py file in use
    from django.urls import reverse
    reverse('blogs',kwargs={'year':'2019','month':'06'})      # 完整URL路径:/blog/2019/06/ 

Fifth, reverse analysis of a namespace mode

  1. urls.py in the project directory

    from django.conf.urls import url, include
    urlpatterns = [
        url(r'^app01/', include('app01.urls', namespace='app01')),
        url(r'^app02/', include('app02.urls', namespace='app02')),
    ]
  2. app01 in urls.py

    from django.conf.urls import url
    from app01 import views
    urlpatterns = [
        url(r'^(?P<pk>\d+)/$', views.detail, name='detail')
    ]
  3. app02 in urls.py

    from django.conf.urls import url
    from app02 import views
    urlpatterns = [
        url(r'^(?P<pk>\d+)/$', views.detail, name='detail')
    ]
  4. Reverse lookup syntax: 'namespace name: URL name'

    • Use in the template
    {% url 'app01:detail' pk=12 %}
    {% url 'app02:detail' pk=12 %}
    • Use the py file
    from django.urls import reverse
    reverse('app01:detail', kwargs={'pk':11})
    reverse('app01:detail', kwargs={'pk':11})
  5. Note: If you have a multi-layer route distribution, with multiple namespace name, the namespace name should be preceded by an alias layer by layer

    {# 简单示例:app01是第一层路由空间的namespace,xxx是第二层路由空间的namespace #}
    {% url 'app01:xxx:index' %}

Guess you like

Origin www.cnblogs.com/zengyi1995/p/11140527.html