Django UrL Parsing

Source: Internet
Author: User

Django's routing system
    • The URLconf essence is the mapping table between the URL and the view function that you want to call for the URL; this is how you tell Django that the logic code that is invoked for a URL that is sent by the client corresponds to execution.

1.1 The URL configuration under Django version 2.0

from django.conf.urls import url  # 支持正则匹配from . import viewsurlpatterns = [    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),]

1.2 Django version 2.0 above the URL configuration defaults to:

from django.urls import path, re_path,register_converter# re_path 与url 一样# path 有几种格式可以选择 一般是自己定义可以,但是需要转换:如下class FourDigitYearConverter(object):    regex = "[0-9]{4}"    def to_python(self, value):        return int(value)    def to_url(self, value):        return "%04d" % valueclass TwoDigitMonthCoverter(object):    regex = "[0-9]{2}"    def to_python(self, value):        return int(value)    def to_url(self, value):        return "%02d" % value# 把自定义的路由匹配规则注册就可以用啦 register_converter(TwoDigitMonthCoverter,"mm")register_converter(FourDigitYearConverter,"yyyy")urlpatterns = [    re_path(r"login/$", views.login, name="login", ),  # 路由分发    re_path(r"index/$", views.index, name="index", ),  # 路由分发    path("atrciles/<mm:month>/", views.active_month),    path("atrciles/<yyyy:year>/", views.active_year),    path("atrciles/<yyyy:year>/<mm:month>/", views.active_ym),]
2.url's famous grouping

In a python regular expression, the syntax for naming a regular expression group is (?). P pattern), where name is the name of the group, pattern is the mode to match

from django.conf.urls import urlfrom . import viewsurlpatterns = [    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),]

This implementation is exactly the same as the previous example, with only one subtle difference: The captured value is passed to the view function as a keyword parameter rather than as a positional parameter

如果Url这样的的时候    '''    /articles/2005/03/ 请求将调用views.month_archive(request, year='2005', month='03')函数,而不是views.month_archive(request, '2005', '03')。    /articles/2003/03/03/ 请求将调用函数views.article_detail(request, year='2003', month='03', day='03')。    '''

This means that your urlconf will be clearer and less prone to errors in parameter order problems

Note that the first match of the successful field needs to be uploaded to the views function, the function needs to accept the parameter, otherwise the error, can be grouped match, the specified format, then the view function also needs to be consistent with the name of the group 3. Distribution
'''At any point, your urlpatterns can “include” other URLconf modules. Thisessentially “roots” a set of URLs below other ones.Including another URLconf    1. Add an import:  from blog import urls as blog_urls    2. Add a URL to urlpatterns:  url(r'^blog/', include(blog.urls))'''from django.conf.urls import include, urlurlpatterns = [   url(r'^admin/', admin.site.urls),   url(r'^cmdb/', include('cmdb.urls')),]
4.url Reverse resolution

A common requirement when using a Django project is to get the final form of the URL for embedding into the generated content (in the view and the URL displayed to the user, etc.) or for handling server-side navigation (redirection, etc.).

There is a strong desire not to hardcode these URLs (laborious, non-extensible and prone to errors) or to design a specialized URL generation mechanism that is not related to urlconf, because it can easily lead to a certain amount of outdated URLs being generated.

In other words, what is needed is a dry mechanism. In addition to the others, it also allows the design of URLs to be automatically updated without traversing the project's source code to search for and replace outdated URLs.

Get a URL The first thing you think about is the identity of the view that handles it (for example, the name), the other necessary information for finding the correct URL has the type of the view parameter (positional parameter, keyword parameter), and value.

Django provides a way to make URL mappings the only place in the URL design. You fill your urlconf and then you can use it in both directions:

    • Based on a user/browser-initiated URL request, it invokes the correct Django view and extracts its parameters from the URL to the desired value.
    • Gets the URL associated with the Django view based on its identity and the value of the parameter that will be passed to it.
      The first way is the usage we've been discussing in the previous chapters. The second way is called reverse parsing the URL, reverse URL match, reverse URL query, or simple URL reverse lookup.

Where URLs are required, Django provides different tools for URL inversion for different levels:

In the template: Use the URL template tag.
In Python code: Use the Django.core.urlresolvers.reverse () function.
In higher-level code related to handling Django model instances: Using Get_absolute_url ()
Method.

URL route distribution to URL name assignment

from django.conf.urls import urlfrom . import viewsurlpatterns = [    #...    url(r'^articles/([0-9]{4})/$', views.year_archive, name='re_year'),    #...]

In the Tempalte template

<a href="{% url 'nre_year' 2012 %}">2012 Archive</a><ul>{% for yearvar in year_list %}<li><a href="{% url 'nre_year' yearvar %}">{{ yearvar }} // yearvar对应的就是每年的数字 Archive</a></li>{% endfor %}</ul>

Use in the Views function

from django.core.urlresolvers import reversefrom django.http import HttpResponseRedirectdef redirect_to_year(request):    year = 2006    url = reverse("re-year", args=("year,)    print(url)    # ...        # ...    return HttpResponseRedirect(reverse('re-year', args=(year,)))    
5. Namespaces

Why do I need to use namespace??

Because name does not have a scope, Django searches the project's global order when it deserializes the URL, and returns immediately when the first name is found to specify a URL
When we develop a project, we often use the Name property to reverse the URL, and when accidentally defining the same name in the URLs of different apps, it can cause the URL to reverse the error, in order to avoid this occurrence, the introduction of namespaces. (Transferred from HANYYYY blogs)

Project. url.py

urlpatterns = [    url(r'^admin/', admin.site.urls),    url(r'^app01/', include("app01.urls",namespace="app01")),    url(r'^app02/', include("app02.urls",namespace="app02")),]

App01.urls:

urlpatterns = [    url(r'^index/', index,name="index"),]

App01.urls:

urlpatterns = [    url(r'^index/', index,name="index"),]

App01.views

from django.core.urlresolvers import reversedef index(request):    return  HttpResponse(reverse("app01:index"))

App02.views

from django.core.urlresolvers import reversedef index(request):    return  HttpResponse(reverse("app02:index"))

Django UrL Parsing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.