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; this is how you tell Django that the logic code that is invoked for a URL that the client is sending corresponds to execution.
Simple routing configuration
From django.urls import path,re_pathfrom app01 Import viewsurlpatterns = [ re_path (R ' ^articles/2003/$ '), views.special_case_2003), Re_path (R ' ^articles/([0-9]{4})/$ ', views.year_archive), Re_path (R ' ^articles/( [0-9] {4}) /([0-9]{2})/$ ', views.month_archive), Re_path (R ' ^articles/([0-9]{4})/([0-9]{2})/([0-9]+]/$ ', Views.article_ Detail),]
Attention:
- To capture a value from a URL, you only need to place a pair of parentheses around it.
- You do not need to add a leading backslash, because each URL has a. For example, it should be
^articles
rather than ^/articles
.
- The ' R ' in front of each regular expression is optional but is recommended to add. It tells Python that the string is "raw"--any character in the string should not be escaped
Example:
"' Some examples of requests: The/ARTICLES/2005/03/request will match the third pattern in the list. Django will call the function views.month_archive (Request, ' 2005 ', ' 03 '). /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/the first pattern in the matching list is not the second, because the pattern matches sequentially, and the first Test matches first. Be free to insert special cases like this to detect the order of the matches. /ARTICLES/2003 does not match any one pattern, because each pattern requires the URL to end with a backslash. The/articles/2003/03/03/will match the last pattern. Django will call the function views.article_detail (Request, ' 2003 ', ' 03 ', ' 03 '). ""
Famous 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:
From django.urls import path,re_pathfrom app01 Import viewsurlpatterns = [ re_path (R ' ^articles/2003/$ '), views.special_case_2003), Re_path (R ' ^articles/(? P<YEAR>[0-9]{4})/$ ', views.year_archive), Re_path (R ' ^articles/(? P<YEAR>[0-9]{4})/(? P<MONTH>[0-9]{2})/$ ', views.month_archive), Re_path (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/articles/2005/03/request will call Views.month_archive (Request, Year= ' 2005 ', month= ' 03 ') function instead of views.month_archive ( Request, ' 2005 ', ' 03 '). the/ARTICLES/2003/03/03/request will call the function views.article_detail (request, year= ' 2003 ', Month= ' ", day= ' 03 '). ""
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;
Distribute
Your urlpatterns can "include" other URLconf modules. Thisessentially "Roots" a set of URLs below other ones. " From django.urls import path,re_path,includefrom app01 Import viewsurlpatterns = [ re_path (R ' ^admin/'), Admin.site.urls), Re_path (R ' ^blog/', include (' Blog.urls ')),]
Reverse parsing
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.
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: using
from django.urls import reverse()函数
the
urls.py:
From Django.conf.urls import Urlfrom. Import Viewsurlpatterns = [ # ... Re_path (R ' ^articles/([0-9]{4})/$ ', views.year_archive, name= ' news-year-archive '), # ...]
In the template:
<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:
From django.urls import reversefrom django.http import httpresponseredirectdef redirect_to_year (Request): # ... Year = 2006 # ... Return Httpresponseredirect (Reverse (' news-year-archive ', args= (year,))) # with redirect ("/path/")
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
.
Name space
The namespace (English: Namespace) is the visible range that represents the identifier. An identifier can be defined in more than one namespace, and its meaning in different namespaces is mutually irrelevant. In this way, any identifiers can be defined in a new namespace, and they do not conflict with any existing identifiers because existing definitions are in other namespaces.
Because name does not have a scope, Django will search in the project's global order when the URL is reversed, and when it finds the first name specifying a URL, it returns immediately when we develop the project, we often use the Name property to reverse the URL. When you accidentally define the same name in a different app's URLs, you can cause the URL to reverse-solve the problem, and in order to avoid this, the namespace is introduced.
urls.py for Project:
Urlpatterns = [ re_path (R ' ^admin/', admin.site.urls), Re_path (R ' ^app01/', include ("App01.urls", namespace= " App01 ")), Re_path (R ' ^app02/', include (" App02.urls ", namespace=" APP02 ")),]
App01.urls:
Urlpatterns = [ re_path (R ' ^index/', index,name= "index"),]
App02.urls:
Urlpatterns = [ re_path (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") )
Path in version django2.0
Think of it as follows:
Urlpatterns = [ re_path (' articles/(? P<YEAR>[0-9]{4})/', year_archive), Re_path (' article/(? p<article_id>[a-za-z0-9]+)/detail/', Detail_view), Re_path (' articles/(? p<article_id>[a-za-z0-9]+)/edit/', Edit_view), Re_path (' articles/(? p<article_id>[a-za-z0-9]+)/delete/', Delete_view), ]
Consider two of these issues:
The first problem is that the year year_archive
parameter in the function is of type string, so you need to convert the value of the variable to an integer type first, year=int(year)
without exceptions such as TypeError or ValueError. So is there a way to do this in the URL so that the conversion step can be done automatically by Django?
The second problem, three routes in the article_id are the same regular expression, but you need to write three times, when after the article_id rule changes, you need to modify the three code at the same time, then there is no way, just modify one place?
In Django2.0, you can use path
the two problems that are resolved above.
Basic example
This is a simple example:
From django.urls import path from . Import urlpatterns = [ 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>/', Views.article_detail), ]
Basic rules:
- Use angle brackets (
<>
) to capture values from the URL.
- The captured value can contain a converter type (converter type), such as using the
<int:name>
capture of an integer variable. If there is no converter, it will match any string and of course include the /
characters.
- You do not need to add a leading slash.
The following is a sample analysis table that is organized according to 2.0 official documents:
Path Converter
The original document is path converters, which translates as a converter.
Django supports the following 5 converters by default:
- STR, which matches a
/
non-empty string other than the path delimiter (), which is the default form
- An int that matches a positive integer that contains 0.
- A slug that matches letters, numbers, and strings that consist of bars and underscores.
- UUID, matching a formatted UUID, such as 075194d3-6885-417e-a8a8-6c931e272f00.
- path, matching any non-empty string that contains the path delimiter
Registering a custom converter
For some complex or reusable needs, you can define your own converters. A converter is a class or interface that requires three points:
regex
Class properties, String type
to_python(self, value)
method, value is the string that the Class property regex
matches to, and the specific Python variable value is returned for Django to pass to the corresponding view function.
to_url(self, value)
method, and to_python
instead, value is a specific Python variable value that returns its string, typically used for URL reverse referencing.
Example:
Class Fourdigityearconverter: regex = ' [0-9]{4} ' def to_python (self, value): return int (value) def to_url (self, value): return '%04d '% value
Use to register_converter
register it in the URL configuration:
From django.urls import register_converter, path from . Import converters, Views register_converter (converters . Fourdigityearconverter, ' yyyy ') urlpatterns = [ path (' articles/2003/', views.special_case_2003), Path ( ' articles/<yyyy:year>/', views.year_archive), ... ]
5 Django-2 routing Layer (URLconf)