The Django View layer Routing configuration system (URLs)

Source: Internet
Author: User

Routing configuration system (URLs) for the view layer

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 that you want to call for that URL ; that's how you tell Django to call that code for that URL and call that code for that URL.

    " "         urlpatterns = [         URL (regular expression, views view function, parameter, alias),] parameter description:    a regular expression string    a callable object, Typically a view function or a string that specifies the path of a view function optional    default argument (dictionary form) to pass to the view function    an optional name    parameter  '
Regular string parameter 1 simple configuration
 fromDjango.conf.urlsImportURL from.ImportViewsurlpatterns= [
  URL (r ' ^admin/', admin.site.urls), #系统生成的映射
url (r "^$", Views.index), #访问http://127.0.0.1:8000, call the index view function, root directory address access URL (r '^articles/2003/$', views.special_case_2003), #表示articles/2003/This path maps the special_case_2003 function URL of the views module (R'^articles/([0-9]{4})/$', views.year_archive), #表示匹配4个0-9 of any numeric 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),]

#注意: The above matches are enclosed in parentheses, and the values inside these parentheses are passed as arguments to the following view functions
" "      Note:    1 Once the match is successful no longer continue    2 to capture a value from a URL, you only need to place a pair of parentheses around it.     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. Some examples of requests:    /articles/2005/3/does not match any URL pattern, because the third pattern in the list requires that the month should be two digits.    /articles/2003/will match the first pattern in the list instead of the second one, because the pattern matches sequentially, the first one tests for a match, and the match succeeds no longer matches . The    /articles/2005/03/request will match the third pattern in the list.
Pass the parameter by location " "
# sets whether the item is open after the URL access address is not/jumps to the path with/ Append_slash=true
SLASH

2 notable groups (named group)

The example above uses a simple, unnamed set of regular expressions (through parentheses) to capture the values in the URL and pass it to the view with positional parameters . In a more advanced usage, you can use named regular expression groups 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 naming a regular expression group 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:

 fromDjango.conf.urlsImportURL from.ImportViewsurlpatterns=[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:

    /articles/2005/03/         Request will call Views.month_archive (request,year ='2005', month= ' Geneva ' The function     /articles/2003/03/03/      request will call the function views.article_detail (request,year =' 2003 'month= ', ' day= ').

In practical applications, this means that your urlconf will be clearer and less prone to errors in parameter order problems-you can rearrange the order of parameters in your view function definition. Of course, these benefits are at the cost of brevity, and some developers believe that named group syntax is ugly and cumbersome.

If a path is named, the corresponding view function must be named as the formal parameter.

Attention:

  Regardless of the matching method used by the regular expression, each captured parameter is passed to the view as a normal Python string

For example, in the following line urlconf:

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

  views.year_archive()The year argument will be a string

3 URLconf on what to look for

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 find 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.

4 specifying default values for view parameters

A handy little trick is to specify the default values for the view parameters. Here is an example of a urlconf and a view:

#URLconf fromDjango.conf.urlsImportURL from.ImportViewsurlpatterns=[url (r'^blog/$', views.page), url (r'^blog/page (? p<num>[0-9]+)/$', Views.page),]#View (in blog/views.py)defPage (Request, num="1"):    ...

In the example above, two URL patterns point to the same view- views.page -but the first pattern does not capture any values from the URL. If the first pattern matches, the page() function uses the num default value "1" for the parameter. If the second pattern matches, the page() value captured by the regular expression is used num .

Alias
Urlpatterns = [    url (r'^reg/$', views.month_views,name=' ) Register'),]

In the static file that is accessed,

<! DOCTYPE html>"en">"UTF-8"> <meta http-equiv="x-ua-compatible"Content="Ie=edge"> <meta name="Viewport"Content="Width=device-width, initial-scale=1"> <title>Title</title>'Post'action='{% Register%}'>xxxx</form></body>

When the path of our backend changes (that is, when the matching rules ^reg/$ need to change), the front-end page if the reference alias {% Register%}, you can not change the front-end of any code, can be properly mapped access.

Reverse parsing of 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 a django.core.urlresolvers.reverse() function.
    • In higher-level code related to handling Django model instances: Using get_absolute_url() methods.

Example:

Consider the following urlconf:

 from Import URL  from Import = [    #...    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 in year_list%}<li><a href="{% url ' news-year-archive ' Yearvar%}">{{Yearvar}} archive</a></li>{% endfor%}</ul>

In Python code, this is done using:

 from Import Reverse  from Import Httpresponseredirect def redirect_to_year (Request):     #  ...    Year = 2006    #  ...    return Httpresponseredirect (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.

Named URL pattern

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 .

DB1
URL (r'^login.html$', views. Login.as_view ()), ============================ fromDjango.viewsImportViewclassLogin (View):defDispatch (self, request, *args, * *Kwargs):Print('before') obj= Super (login,self). Dispatch (Request, *args, * *Kwargs)Print(' After')        returnobjdefGet (self,request):returnRender (Request,'login.html')     defPost (self,request):Print(Request. Post.get ('User'))        returnHttpResponse ('Login.post')
View Code

Routing app distribution

If you have a lot of web sites and many apps, you'll need a lot of routing to distribute. If all routing distributions are placed under the urlconf file, which makes the file less manageable, we can create a urls.py file for each app and then include the urls.py file in the Urlpatterns in urlconf.

 from Import # Import Global URLurlpatterns = [    url (r'^blog', include ('  Blog.urls'),   # Distribute the access path to the path at the beginning of the blog to the urls.py module under App1 for route mapping ]

This way, in the URL of our Blog-app, we hold all the URL distribution work about the blog.

Urlpatterns = [    url (r'^2004/$', year_2004),         URL (r' ) ^ (\d{4})/$ ' , year_query),         URL (r'^ (\d{4})/(\d{2}) $', Year_query),         URL (r'^ (? P<YEAR>\D{4})/(? P<MONTH>\D{2}) $', Year_query),    ]

So our visit to the site should be: HTTP://127.0.0.1:8080/BLOG/2012/3 before you have to bring the name of the app

Routing configuration system (URLs) for the Django View layer

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.