Django's URLs system

Source: Internet
Author: User

A brief introduction to Django's URLs system

Django 1.11 version urlconf official documentation

The URL configuration (URLconf) is like the directory of the Web site that Django supports. Its essence is the mapping table between the URL and the view function to be called for the URL .

That's how you tell Django to call that code for that URL and call that code for that URL.

Urlconf Configure the basic format:
From django.conf.urls import urlurlpatterns = [     URL (regular expression, views view function, parameter, alias),]

  

Attention:

The routing system in the Django 2.0 version has been replaced by the following notation (official documentation):

From django.urls import pathurlpatterns = [    path (' articles/2003/', views.special_case_2003),    path (' articles/ <int:year>/', views.year_archive),    path (' articles/<int:year>/<int:month>/', views.month_ Archive),    path (' articles/<int:year>/<int:month>/<slug:slug>/', Views.article_detail),]

  

Parameter description:
    • Regular expression: a regular expression string
    • Views View function: A callable object, typically a view function or a string that specifies the path of a view function
    • Parameters: Optional default parameters to be passed to the view function (in dictionary form)
    • Alias: An optional name parameter
Regular expression detailed basic configuration
From Django.conf.urls import Urlfrom. 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),]

  

Precautions
    1. The elements in the Urlpatterns match the regular expression from top to bottom in the writing order, and once the match succeeds, it will no longer continue.
    2. To capture a value from a URL, simply place a pair of parentheses around it (grouping matches).
    3. You do not need to add a leading backslash, because each URL has a. For example, it should be ^articles rather than ^/articles.
    4. The ' R ' in front of each regular expression is optional but is recommended to add.
Additional Information
# whether to turn on configuration items that are not followed by/jump to the path with/after the URL access address Append_slash=true

  

This parameter is not append_slash by default in the Django settings.py configuration file, but the Django default parameter is Append_slash = True. The function is to automatically add '/' at the end of the URL.

The effect is:

We define the urls.py:

From django.conf.urls import urlfrom app01 Import viewsurlpatterns = [        url (R ' ^blog/$ ', Views.blog),]

  

When you access Http://www.example.com/blog, the URL is automatically converted to http://www.example/com/blog/by default.

If append_slash=falseis set in settings.py, we will be prompted to ask for Http://www.example.com/blog when the page is not found.

Grouping named matches

The example above uses a simple regular expression grouping match (with parentheses) to capture the value in the URL and pass it to the view as a positional parameter.

In more advanced usages, you can use a group of regular expressions that group named matches to capture the values in the URL and pass it to the view as a keyword argument.

In a python regular expression, the syntax for grouping named regular expression groups is the name of the (?P<name>pattern) group, which is the name pattern pattern to match.

Here are the overrides for the above urlconf using named groups:

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.

For example, the URL /articles/2017/12/ is equivalent to invoking a view function as follows:

Views.month_archive (Request, year= ", month=" 12 ")
urlconf Matching Location

URLconf looks up at the requested URL and considers it as a normal Python string. Get and Post parameters and domain names are not included.

For example, in a http://www.example.com/myapp/request, URLconf will look for myapp/.

In the http://www.example.com/myapp/?page=3 request, URLconf will still be looking myapp/ .

URLconf does not check the requested method. In other words, all the request methods-the same URL, and POST GET HEAD so on-are routed to the same function.

The captured parameters are always strings

Each parameter captured in the urlconf is passed to the view as a normal Python string, regardless of the matching method used by the regular expression. For example, in the following line urlconf:

URL (r ' ^articles/(? P<YEAR>[0-9]{4})/$ ', views.year_archive),

  

The argument passed to views.year_archive() the view function year is always a string type.

Specifying default values in view functions
# urls.py from Django.conf.urls import Urlfrom. Import viewsurlpatterns = [    url (R ' ^blog/$ ', views.page),    url (r ' ^blog/page (? p<num>[0-9]+)/$ ', views.page),]# views.py, you can specify the default def page for Num (request, num= "1"):    Pass

  

In the example above, two URL patterns point to the same view-views.page-but the first pattern does not capture anything from the URL.

If the first pattern matches, the page () function uses its default parameter num= "1", and if the second pattern matches, the page () will use the NUM value captured by the regular expression.

Include other Urlconfs
#At any point, your urlpatterns can "include" and other URLconf modules. This#essentially "Roots" a set of URLs below other ones. #For example, here's a excerpt of the URLconf for the Django webs ITE itself. #It includes a number of other Urlconfs:from django.conf.urls import include, urlurlpatterns = [   url (r ' ^adm In/', admin.site.urls),   url (r ' ^blog/', include (' Blog.urls ')),  # can contain other URLCONFS files]

  

Pass additional arguments to the View function (learn)

Urlconfs has a hook that lets you pass a Python dictionary as an additional parameter to the view function.

django.conf.urls.url()The function can receive an optional third parameter, which is a dictionary that represents the extra keyword arguments that you want to pass to the view function.

For example:

From Django.conf.urls import Urlfrom. Import viewsurlpatterns = [    url (R ' ^blog/(? P<YEAR>[0-9]{4})/$ ', views.year_archive, {' foo ': ' Bar '}),]

  

In this example, for the/blog/2005/request, Django will invoke views.year_archive (Request, Year= ' 2005 ', foo= ' bar).
This technique is used in the syndication framework to pass metadata and options to the view.

Named URLs and 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: Use the Get_absolute_url () method.

It says a whole bunch of them, and you may not be able to read them. (That's a blunt translation of official documents).

Let's simply say that we can give a name to our URL matching rule, a URL matching pattern.

So we don't have to write dead URL code anymore, we just need to call the current URL by name.

To give a simple example:

URL (r ' ^home ', views.home, name= ' home '),  # give me the URL matching pattern named Homeurl (R ' ^index/(\d*) ', Views.index, name= ' index '),  # give me the URL match pattern named index

  

Such

This can be referenced in the template:

{% url ' home '%}

  

This can be referred to in the views function:

From Django.urls import reversereverse ("Index", args= ("2018",))

Example:
Consider the following urlconf:

From Django.conf.urls import Urlfrom. Import Viewsurlpatterns = [    # ...    URL (r ' ^articles/([0-9]{4})/$ ', views.year_archive, name= ' news-year-archive '),    # ...]

  

According to the design here, the URL of the corresponding archive for a certain year nnnn is /articles/nnnn/ .

You can use the following methods in the template's code to get them:

<a href= "{% url ' news-year-archive ' +%}" >2012 archive</a><ul>{% for Yearvar in Year_list%}<LI&G T;<a href= "{% url ' news-year-archive ' Yearvar%}" >{{Yearvar}} archive</a></li>{% endfor%}</ul >

  

In Python code, this is done using:

From django.urls import reversefrom django.shortcuts import redirectdef redirect_to_year (Request):    # ...    Year = 2006    # ...    Return Redirect (reverse (' news-year-archive ', args= (year,)))

  

If for some reason you decide that the URLs that are published by year-to-date articles should be adjusted, then you will only need to modify the content in urlconf.

In some scenarios, a view is generic, so there is a many-to-one relationship between URLs and views. For these cases, when you reverse the URL, only the name of the view is not enough.

Attention:

In order to complete the URL inversion in the example above, you will need to use the named URL pattern. The name of the URL uses a string that can contain any character you like. Not limited to the legal Python name.

When naming your URL pattern, make sure that the name you use does not conflict with names in other apps. If your URL pattern is called comment , and another application has the same name, you cannot guarantee which URL will be inserted when you use the name in the template.

Adding a prefix to the URL name, such as the name of the app, will reduce the likelihood of a conflict. We recommend using myapp-comment rather than comment .

namespace mode

Even if different apps use the same URL name, the namespace mode of the URL allows you to reverse the named URL only.

As an example:

urls.py in Project

From Django.conf.urls import URL, include urlpatterns = [    url (R ' ^app01/', include (' App01.urls ', namespace= ' app01 ')) ,    URL (r ' ^app02/', include (' App02.urls ', namespace= ' app02 ')),]

  

The urls.py in APP01

From django.conf.urls import urlfrom app01 import views app_name = ' app01 ' urlpatterns = [    url (r ' ^ (? p<pk>\d+)/$ ', views.detail, name= ' detail ')]

  

The urls.py in APP02

From django.conf.urls import urlfrom app02 import views app_name = ' app02 ' urlpatterns = [    url (r ' ^ (? p<pk>\d+)/$ ', views.detail, name= ' detail ')]

  

Now, the URL name is duplicated in my two apps, and I can get my current URL by the name of the namespace when I reverse the URL.

Grammar:

' namespace name: URL name '

Used in templates:

{% url ' app01:detail ' pk=12 pp=99%}

  

Use in functions in views

v = reverse (' app01:detail ', kwargs={' PK ': 11})

  

So even if the URL in the app is named the same, I can reverse the correct URL.

Django's URLs system

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.