Django static and dynamic routing

This is the 17th day of my participation in the August More text Challenge. For details, see:August is more challenging

1. Include Route distribution

1.1 Create a new urls.py in the app

from django.conf.urls import url
from app01 import views
​
urlpatterns = [
    url(r'^blog/$', views.blog),
    url(r'^blogs/([0-9]{4})/$', views.blogs,{"k1":"v1"}), # blogs/2012/
]
Copy the code

1.2 Change the contents of the original project in urls.py to include

from django.conf.urls import url,include from django.contrib import admin urlpatterns = [ url(r'^admin/', Admin. Site. Urls), # url (r '^ app01 /', include (" app01. Urls ")), # http://127.0.0.1:8000/app01/blogs/2002/ url (r '^', App01. The urls include (" ")), if is empty] # http://127.0.0.1:8000/blog/Copy the code

The contents of the urls.py parameter can be empty (in effect, wrap the original urls.py parameter into the app, and make the app call urls.py with include())

2, URL naming and reverse resolution

Set an alias just like as

2.1 Static Route

Name: url(r'^blogs/$', views.blogs, name="bloogs"), # set an alias to bloggs: <a href="{% url 'bloogs' %}"> <a href="{% url 'bloogs' %}"> <a href="{% url 'bloogs' %}" From Django.shortcuts import reverse # There are two ways to import from Django.urls import reverse print(reverse("bloogs")) #/blogs/ ' 'Copy the code

2.2 Dynamic Routing

- grouping ` ` ` url (r ^ 'blogs/([0-9] {4})/(\ d {2}) $', views, blogs, name = "bloogs"), ` ` ` reverse DNS: <a href="{% url 'bloogs' '2002' '02' %}"> </a> Py print(reverse("bloogs",args=(2002,99))) # /blogs/2002/99 - named group group url(r'^blogs/(? P<year>[0-9]{4})/(? P < method > \ d {2}) $', views, blogs, name = "bloogs"), ` ` ` reverse DNS: Template ` ` ` # {< a href = "{% url 'bloogs',' 2002 ' '02' %}" > test url naming and reverse DNS #} < / a > < a href = "# this want to corresponding parameters {% url 'bloogs' method =' 99 ' Year ='2000' %}"> test url name and reverse resolution </a> # /blogs/2002/99 print(reverse("bloogs",kwargs={"year":"2009","method":99})) # /blogs/2009/9 ```Copy the code

3. Namespace

app01 urls.py: urlpatterns = [ url(r'^home/$', views.home, name='home') ] app02 urls.py: Urlpatterns = [url(r'^home/$', views.home, name='home')] {% url 'home' %} App02's home overwrites app01's homeCopy the code

To avoid this, add a namespace

Urlpatterns = [url(r'^admin/', admin.site.urls), url(r'^app01/', include("app01. Urls ", namespace="app01")), url(r'^app02/', include("app02.urls", namespace="app02")), ]Copy the code

Just adding a namespace doesn’t work either. When we use reverse parsing and PY, we also need to distinguish and add where appropriate

Reverse parsing: {% url 'app01:home' %} {% url 'app02:home' %} py print("app01:home")) # /app01/home/ print(reverse("app02:home")) # /app02/home/Copy the code