Django's routing system

Source: Internet
Author: User

urlconf ConfigurationBasic Format:
 from Import  = [    URL (regular expression, views view function, parameter, alias)]

Note: The routing system in the Django2.0 version has been replaced by the following notation

 from Import  = [    path ('class/1994/', views.class_1994),    Path ( ' class/<int:year>/<int:month>/ ' , Views.class_year_month),]

Reference notes:

1) Regular expression: a regular expression string

2) Views View function: A callable object, usually a view function or a string that specifies the path of the view function

3) Parameters: Optional default parameters to be passed to the view function (in dictionary form)

4) Alias: An optional name parameter

Regular expression detailed basic configuration
 from Import URL  from Import  = [    url (r'^class/([0-9]{4})/([0-9]{2})/([0-9]+)/$', Views.class_detail)]
Precautions:

1) The elements in the urlpatterns from the top down to match the regular expression, once the matching success is not continue down.

2) to capture a value from the URL, 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: ^class instead of ^/class.

4) the ' R ' in front of each regular expression is optional but is recommended to add.

Additional notes:
# whether to turn on the top of the configuration that does not follow/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 Django defaults to this append_slash = True. The function is to add "/" at the end of the URL.

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 (views) as a positional parameter.

In a more advanced usage, you can use a grouping of regular expression groups of named matches to capture the values in a URL and pass it to the view (views) as a keyword argument.

In Python regular expressions, the syntax for grouping named regular expression groups is (?). P<name>pattern), where name is the name of the group, pattern is the mode to match.

  

 fromDjango.conf.urlsImportURL from.ImportViewsurlpatterns=[url (r'^class/2003/$,views.class'), url (r'^student/(? P<YEAR>[0-9]{4})/(? P<MONTH>[0-9]{2})/$'), views.year_month), url (r'teacher/(? P<YEAR>[0-9]{4})/(? P<MONTH>[0-9]{2})/$'), Views.teacher_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 url/teacher/2018/10/the equivalent of invoking the view function as follows:

Views.teacher_detail (request,year='2018', month=')

In practical applications, the use of group naming matching can make your urlconf more explicit and less prone to errors in parameter order problems.

urlconf Matching Location

Urlconf looks on the requested URL as a normal Python string, excluding the get and post parameters and the domain name.

In http://www.example.com/myapp/?page=3 requests, urlconf will look for myapp/.

Urlconf does not check the requested method. In other words, all the request methods-the same URL's post,, and so on-will all be 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: The following line urlconf:

URL (r'^class/(? P<YEAR>[0-9]{4})/$', Views.year_class),

The year parameter passed to the View function Views.year_class () is always a string type.

Specifying default values in view functions
#in urls.py fromDjango.conf.urlsImportURL from.ImportViewsurlpatterns=[url (r'^blog/$', views.page), url (r'^blog/page (? p<num>[0-9]+)/$', Views.page),]#views.py, you can specify a default value for numdefPage (request,num="1"):    Pass
Include other Urlconfs
 from Import  = [    url (r'^admin/', admin.site.urls),    URL (r')  ^blog/', include ('blog.urls')),  # can contain other URLCONFS files ]
Named URLs and URL reverse resolution

You can give us a URL matching rule name, a URL matching pattern from a name.

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

A simple example:

URL (r"^home$", views.home,name="home"),  # give me the URL match pattern named homeURL (r'^index/(\d*)', views.index,name=' Index '),  #  give me the URL match pattern named index

In the template (which can be understood as an HTML file), you can refer to this:

" Home " %}

This can be referred to in the views function:

 from Import reverseredirect (Reverse ("index", args= ("2018",)) )

Example:

 from Import URL  from Import  = [    url (r'^ (class|student|teacher) _list/$', Views.list, name= ' List ' ),]

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

<liclass="{% block class_active%}{% endblock%}"><a href="{% url ' list ' class '%}"> class List </a></li><liclass="{% block student_active%}{% endblock%}"><a href="{% url ' list ' ' Student '%}"> Student List </a></li><liclass="{% block teacher_active%}{% endblock%}"><a href="{% url ' list ' ' teacher '%}"> Teacher List </a></li>

Use in Python code:

def Delete (request, table, del_id):     = GetAttr (models, Table.capitalize ())    table_Class.objects.get (id=del_id). Delete ()      returnreturn Redirect (reverse ('list'#  The ID passes an ID in order to match the success. 
namespace mode

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

As an example:

urls.py in Project

 fromDjango.conf.urlsImportUrl,includeurlpatterns=[url (r'^app01/', Include ('App01.urls', namespace='APP01')), url (r'^app02/', Include ('App02.urls', namespace='APP02')),]

The urls.py in APP01

 from Import URL  from Import  'app01'= [    url (r'^ (? p<year>\d+)/$', views.detail,name='detail')]

The urls.py in APP02

 from Import URL  from Import  'app02'= [    url (r'^ (? p<year>\d+)/$', views.detail,name='detail')]

The URL in the two app is named repeatedly, and when you reverse the URL, you get the current URL through the name of the namespace.

Grammar:

"namespace name: URL name"

Used in templates:

' App01:detail ' year=1994%}

Use in functions in views

v = reverse ('app01:detail', kwargs={'year': 1994})

This way, you can reverse the correct URL.

Django's routing 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.