Django's urls (routing)

Django's urls (routing)

URL configuration (URLconf) as the Django directory site support.

Its essence is a mapping table between the URL and the URL you want to call that view function.

In this way we are told Django, which encountered URL of time, to which the corresponding function is executed.

The basic format:

from django.conf.urls import url

urlpatterns = [
  url(正则表达式, views视图函数,参数,别名),
]

Parameter Description

  • Regular Expressions: A regular expression string
  • views view: a callable object, a view is generally a function of
  • Parameters: The optional parameters to be passed to the default view function (a dictionary)
  • Alias: An optional parameter name

django 2.0 version of the routing system

Re_path version 2.0 and version 1.11 of the url is the same usage

from django.urls import path,re_path
urlpatterns = [
 path('articles/2003/', views.special_case_2003),
]


Detailed regular expressions

basic configuration

from django.conf.urls import url

from . import views

urlpatterns = [
 url(r'^articles/2003/$', views.special_case_2003),
 url(r'^articles/([0-9]{4})/$', views.year_archive),
 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),
]

Precautions:

  1. urlpatterns elements in the writing order from the top one by matching a regular expression, once the match is successful discontinued.
  2. To capture a value from the URL, only to place a pair of parentheses (packet matches) around it.
  3. No need to add a leading backslash, because each URL has. For example, it should be ^ articles, not ^ / articles.
  4. Each regular expression in front of the 'r' is optional, but suggested adding.

Additional information:

  1. Whether open access URL address is not behind / jump to the path with / of configuration items: APPEND_SLASH = True
  2. Django default configuration file is not the settings.py APPEND_SLASH this parameter, but this parameter is default Django APPEND_SLASH = True / False, its role is automatically added at the end of the URL '/'


Matching routing (packet match)

:( packet is to give some regular expression parentheses) using a simple regular expression match packet () to capture the value of the URL by parentheses and passing parameters to the position in view of the function

In Python regular expressions, the group named regular expression syntax group is (?P<name>pattern), which nameis the name of the group, patternis the pattern to match.

Here is rewritten named group

from django.conf.urls import url

from . import views

urlpatterns = [
 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 identical to the previous example, only a subtle difference: the captured value as a key instead of the position parameter transfer function parameters to view.

For example, for a url / articles / 2017/12 / corresponding to the view function calls in the following manner:

views.month_archive(request, year="2020", month="1")

Unknown group

When matching routes, to a certain regular expressions added brackets

When matching the regular expression parentheses will be matched to the position of the content as the corresponding view parameters passed to the function

url(r'^test/([0-9]{4})/',views.test)

View function

def index(request, args):
  return HttpResponse('KAI')

Famous grouping

To some regular expression from an alias

When the contents match the regular expression within the brackets will, as keyword arguments passed to the corresponding view function

url(r'^test/(?P<year>\d+)/',views.test)

View function

def index(request,year):
  return HttpResponse('KAI')          

supplement:

Unknown group and famous grouping can not be mixed

Although the same can not be mixed but can use multiple naming

url(r'^test/(?P \d+)/(?P \d+)/',views.test)

Reverse lookup

Some methods can be obtained by a result of the result url to access the corresponding

Imagine a scenario where you have more than 200 a label, href point to the index /,

One day in urls inside index changed to new_index, then you can only change a tag href manual

When you change the finish, it is a my_index, then the time of day may change the address, then there is no way, no longer write the program die, reverse analysis is applied to this.

Use:

Give the routing function and view correspondence between a name

url(r'^testadd/',views.testadd,name='add')

Front-end analytical

{% url 'add' %}

Back-end analytic

from django.shortcuts import render,HttpResponse,redirect,reverse
  reverse('add')

Unknown Packet reverse lookup

url(r'^testadd/(\d+)/',views.testadd,name='add')

Front-end analytical

{% url 'add' 1 %}

Back-end analytic

reverse('add',args=(1,))

Famous grouping reverse lookup

url(r'^testadd/(?P<year>\d+)/',views.testadd,name='add')

Front-end analytical

URL% { 'the Add'. 1%} # recommended

URL% { 'the Add' year =%}. 1 # Standard

Back-end analytic

reverse('add',args=(1,))

reverse('add',kwargs={'year':1})

Route distribution

When django project is relatively large when the routing function and view correspondence relationship more

The total routing code is too long

Taking into account the total routing code is bad maintenance django support each app can have its own urls.py

And the total route no longer do a correspondence relationship routing and view function but merely a distribution task operations only

Depending on the identified request the current request needs to access the function belongs app then automatically

Issued to the corresponding app urls.py inside and then made to match the view routing function by app inside urls.py

Not only that in addition to each app can have its own urls.py addition can also have its own static template file folder templates

Additional become simple django-based sub-group would develop based on the above characteristics

Only you need to create a project django empty after each person only needs to develop its own app

The multi-profile individuals app all copies of the registration project

The total route distribution once

Module requires a distribution

from django.conf.urls import url,include

url(r'^app01/',include('app01.urls')),

url(r'^app02/',include('app02.urls'))

Sub-routing

from django.conf.urls import url
from app01 import views

urlpatterns = [
url(r'^index/',views.index)
]

from django.conf.urls import url
from app02 import views

urlpatterns = [
url(r'^index/',views.index)
]


Namespaces

url(r'^app01/',include('app01.urls',namespace='app01'))
url(r'^app02/',include('app02.urls',namespace='app02'))
后端解析
reverse('app01:index')
reverse('app02:index')
前端解析
{% url 'app01:index' %}
{% url 'app02:index' %}
# 在给路由与视图函数起别名的时候只需要保证永远不出现冲突的情况即可
# 通常情况下我们推荐期别名的时候加上当前应用的应用名前缀

url(r'^index/',views.index,name='app01_index')
url(r'^index/',views.index,name='app02_index')

Virtual Environment

We want to do for different projects to install only the items needed for functional modules

When consumed less than the item and will not be installed to avoid loading resources

How to create a virtual environment

Virtual environment is similar to a pure python interpreter environment

Each vernacular to create a virtual environment you would like to re-download a python interpreter

Virtual environments do not recommend that you use too much

Learning stage we still use environment of the machine can be fitted to all modules all under native environment

Pseudo-static

url ending with .html gives the impression as if the contents of this document was written dead will not easily change

In order to improve your site are collected by search engines SEO efforts to provide efficient query site

Guess you like

Origin www.cnblogs.com/kai-/p/12158918.html