Routing System (urls.py)

Source: Internet
Author: User
Tags aliases call back

routing System (urls.py)Regular expression matching

urls.py

 from django.conf.urls Import URL  from  = [    url (r'^articles/2003/$', views.special_case_2003),    URL (r'^articles/([0-9]{4})/$', views.year_archive),]
The routing system in the Django 2.0 version has been replaced by the following notation
 fromdjango.urls Import Pathurlpatterns=[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:slug>/', Views.article_detail),]
1. Basic format:
 from django.conf.urls import Urlurlpatterns=[url (regular expression, views view function, parameter, alias),]url (R'^delete _book/$', Views.delete_book), #严谨起见, plus Terminator $
Regular expression: a regular expression string
Views View function: A callable Object
Parameters: Optional default parameters to be passed to the view function (in dictionary form)
Alias: An optional name parameter
Note the point:
1. The elements match the regular expression from top to bottom in the writing order, and once the match succeeds, it will no longer continue.
/delete_book/?id=5 match to Delete_book in URLs, execute function, no longer match? Id=5
2. To capture a value from a URL, simply place a pair of parentheses around it (group match)
URL (r ' ^delete_book/(\d) $ ', Views.delete_book)
On a page request, you must have a number after delete_book/num, otherwise the match is not equivalent to wearing a parameter for the backend
3. You do not need to add a leading backslash because each URL has a. For example, it should be ^articles rather than ^/articles.
4. The ' R ' in front of each regular expression is optional, but it is recommended to add
URL forward parsingGroup Matching ()equivalent to passing positional arguments to a view function1. Group matching: The contents of the parentheses are captured as arguments passed to the execution function
URL (r'^delete_book/([0-9]{4})/([0-9]{2})/$', Views.delete_book), Def Add_book ( Request):p The/delete_book/error is only entered on the Web page , because three parameters were passed to the function, and the function received only one add_book (REQUEST,ARG1,ARG2): Pass
2. Use group matching to complete the deletion of books
1. URL (r'^delete_book/([0-9]+)/$', Views.delete_book)2. def delete_book (request,del_id):ifDel_id:del_obj=models. Book.objects.Get(id=del_id) del_obj.delete ()returnredirect"/book_list/")    Else:        returnHttpResponse ("The book you want to delete does not exist")
In 3.HTML
<a class= "btn btn-danger" href= "/delete_book/{{book.id}" > Delete </a>
Look for the/delete_book/num/in the URLs, find out the corresponding function, {{book.id}} as a parameter
Grouping named matches
In a python regular expression, the syntax for naming a regular expression group is (?). P<name>pattern), where name is the name of the group, pattern is the mode to match.
Equivalent to passing a keyword argument to a view function. group matching and group naming matching cannot be mixed
URL (r ' ^delete_book/(? p<id_code>[0-9]+)/$ ', Views.delete_book)
The name of the parameter is Id_code, and when the function is received, it is received as a keyword
def delete_book (Request,id_code):p The Id_code can also be replaced **kwargs
Equivalent to Def delete_book (Request,id_code=none):p the Id_code
With Id_code This variable comes in, the value of Id_code is the value of the transmitted
This makes the urlconf more clear and less prone to errors in parameter order problems
Group matching requests and? Name=num Request Summary1.? Name=num Request:
URLconf looks for it as a normal Python string on the requested URL. Get and Post parameters and domain names are not included.
For example, in an http://www.example.com/myapp/request, URLconf will look for myapp/. , URLconf will still look for myapp/in the http://www.example.com/myapp/?id=3 request. 
? id=3 is encapsulated as a parameter in the request. function receives only one parameter of request
Request to send id=5 as a dictionary to backend {id:3} back-end function does not need to receive parameters, use request. Get.get
def delete_book (request):    print (Request. GET) #<querydict: {'ID': ['5']}>    Print ( Request. GET. Get ("ID")) #3
2. Group Matching
When using a grouping match, you also need to receive parameters other than request, directly receive this parameter can be used
Back end needs to receive
def delete_book (request,id):    print (ID) #接收到的参数可直接用
3. The captured parameters are always strings4. Specify default values in the View function
Urlpatterns = [    url (r'^blog/$', views.page),    URL (r' ) ^blog/pag (? p<num>[0-9]+)/$', views.page), #只捕获括号里包的内容]# views.py, you can specify the default def page for NUM (request, num ="1"):    Pass
Two URL patterns point to the same view-views.page-but the first pattern doesn't capture anything from the URL.
If the first pattern matches, the page () function uses its default parameter num= "1", and if the second pattern matches, the page () will use the NUM value captured by the regular expression.
routing distribution include
    
1. New app python manage.py startapp app01
2. Add ' App01.apps.App01Config ' to Installed_apps in setting,
3. Create a new URLs file in App01, the URLs in your project are equivalent to a first-level route, and URLs in APP01 are equivalent to level two routing
4. Add a profile to the URLs in App01
 from   Django.conf.urls Import URL import the views file in the same file can be used  from   import Views can also  from   APP01 Import Viewsurlpatterns  =[url (r   " ^delete_book/(? p<id_code>[0-9]+)/$   " , Views.delete_book)] Add relationship  
   5. Operate in a first-level route:   
You need to first import the include module from the Django.conf.urls Import include
re-import URLs in App01 from APP01 import URLs
to add a corresponding relationship in Urlpatterns:
URL (r ' ^app01/', include (URLs)) The request to the beginning of the APP01 to two-level route processing
on the Web page http://127.0.0.1:8000/delete_book/Web page cannot be found, in the first-level route, there is no path beginning with Delete_book
need to add APP01 http://127.0.0.1:8000/app01/delete_book/
6. When importing URLs for multiple apps in a first-level route, for the sake of difference, Use
to take aliases
 from  as App01_urls  from  as App02_urlsurl (R'^app01/', include (app01_urls)) URL (r' ^app01/ ', include (App02_urls))
7. Can also pass additional parameters, in the two-level route to the parameter, in the form of a dictionary  is not commonly used
such as: In App01 's URLs
URL (r ' ^house/', views.house,{"age": 18})
To receive in the execution function:
def house (Request,args): #如是age. The display 18
Print (args) gets the dictionary
URL Reverse resolution reserve
In simple terms, you can give us a name for the URL matching rule, a URL matching pattern with a name.
There is no need to write dead URL code in the future, just call the current URL by name.
In the URL:
Previous format: URL (r'^book_list/$', views.book_list),1. Using URL parsing: url (r'  ^book_list/$', views.book_list,name="check_book"),
References in HTML templates:
class="btn btn-danger" href="/delete_book/?id={{book.id}} > Delete </a>class="btn btn-danger" href="  {% url ' check_book ' book.id%}'> Delete </a>#}
Views in reference to use reverse:
return Redirect ("/book_list/" from django.urls Import Reverse def del_book (request)       Rediret_url=reverse (check_book)      return Redirect ( Rediret_url)
Summary:
  1. How do I get an alias?   

2. How do I use it?
1. Use in template language:
{% url ' alias '%}-get specific URL path
2. How to use in Views:
from Django.urls Import Reverse
reverse ("aliases")--get a specific URL path
Strong>3. How do I pass parameters?
1. In the template language:
{% url" alias "2018" NB "%}
2. In the view function: primarily for redirection
def del_book (Request) #不接收参数. If you use redirection to capture a value, you need to accept the parameter pass positional parameter: It's a meta-ancestor reverse_red=reverse ("aliases", args= (2018,"NB")) #参数在这里传returnRedirect (reverse_red) keyword argument: is a dictionary reverse ("aliases"kwargs={" Year":2018,"title":"NB"})
name Space
Because name does not have a scope, Django searches the project's global order when it deserializes the URL, and returns immediately when the first name is found to specify a URL
Accidentally defining the same name in a different app's URLs may result in a URL inverse error, in order to avoid this happening, the namespace is introduced.
urls.py for Project:
Urlpatterns =[url (r'^admin/', admin.site.urls), url (r'^app01/', Include ("App01.urls",namespace="APP01")), url (r'^app02/', Include ("App02.urls",namespace="APP02")),]
App01.urls:
Urlpatterns = [    url (r'^index/', index,name="Index "),]
App02.urls:
Urlpatterns = [    url (r'^index/', index,name="index") ),]

Views

 from django.core.urlresolvers Import reversedef Index (Request):     return  HttpResponse (Reverse ("app01:index")) app02.views from django.core.urlresolvers Import reversedef Index (Request):
summary
  1. Five steps to request a Django route assignment:   
1. Start looking for
Settings 3. Iterate through the list above, match it, and stop immediately if it matches, call back the function
4. Parameters can be passed when the function is called
5. If the entire list does not match, Throws an exception
2.URL forward:
1. If there is a grouping match in the regular expression, the position parameter is passed
Span style= "font-size:18px" > 2. If there is a named grouping match in the regular expression, the keyword argument

3. Reverse Parse URL: alias the regular expression, and then reverse the image around the real URL by alias
4. Print (Request.get_full_path ()) # Gets the path and parameters of the current request
print (request.path_info) # Takes the path of the current request






Routing System (urls.py)

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.