8. url routing

1. Single route correspondence

url(r'^index/$', views.index),

It should be noted here that /$ means that only those ending with / are valid. If the $ symbol is removed, this url will be matched as long as it starts with index/ .

   

2. Regular routing

   

url(r'^index/(\d*)', views.index),

url(r'^manage/(?P<name>\w*)/(?P<id>\d*)', views.manage),

   

3. Add additional parameters

   

url(r'^manage/(?P<name>\w*)', views.manage,{'id':333}),

   

4. Set the name for the route map

   

url(r'^home', views.home, name='h1'),

url(r'^index/(\d*)', views.index, name='h2'),

After setting the name, it can be called in different places, such as:

   

Use generated URL in template {% url 'h2' 2012 %}

The generated URL reverse('h2', args=(2012,)) path is used in the function : django.urls.reverse , the reverse method provided by django must be used .

   

5. Classify routing rules according to app

   

Set it up in main url.py

url(r'^org/', include('organization.urls',namespace='org')),

   

organization.urls represents the file name, that is to say, as long as it is the url in the org domain, I will go to the organization.urls file to find it. For example www.127.0.0.1:8000/org/list/ etc.

   

6. Namespace

   

a. project.urls.py

   

from django.conf.urls import url,include

 

urlpatterns = [

url(r'^a/', include('app01.urls', namespace='author-polls')),

url(r'^b/', include('app01.urls', namespace='publisher-polls')),

]

   

   

   

After defining the url with the namespace above , when using the name to generate the URL , it should be as follows:

v = reverse('author-polls:detail', kwargs={'pk':11})

{% url 'author-polls:detail' pk=12 pp=99 %}

   

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325079888&siteId=291194637