"Python"--Django Routing system (URL relationship mapping), views, templates

Source: Internet
Author: User

Django routing system (URL relationship mapping), views, templates

I. Routing system (URL relationship mapping)

1, the single route corresponds to:

A URL corresponds to a view function (Class)

Urls.py:url (R ' ^test ', views.test), #url (R ' ^home ', views. Test.as_view ()), Views.py:def Test (Request):    print (Request.method)    return render (Request, "home.html") "" " Class Test (View):    def get (self, request):        print (Request.method)        return render (Request, "home.html")    def post (self, request):        print (Request.method)        return render (Request, "home.html") "" "

  

2, based on the regular route corresponding:

Multiple URLs corresponding to one view

urls.py# multiple URLs correspond to a view function, but when you pass parameters to the view function, the URL of the parameter (R ' ^detail-(\d+)-(\d+). html ', Views.detail), and the URL for the corresponding parameter, Recommend this kind of writing, after the regular match completes the grouping assignment, when passes the parameter to be possible the parameter position change also does not have the relation URL (r ' ^detail-(? p<nid>\d+)-(? p<uid>\d+). html ', Views.detail), views.py: #普通传参def detail (Request, NID, UID):    print (NID, UID)    return HttpResponse ("%s-%s"% (Nid, UID)) #args传参def detail (request, *args, **kwargs):    print (Args[0], args[1])    return HttpResponse ("%s-%s"% (Args[0], args[1])) #kwargs传参def detail (request, *args, **kwargs):    print (kwargs["Nid"), kwargs["UID"])    return HttpResponse ("%s-%s"% (kwargs["nid"], kwargs["UID"])

3. Name:

Name the URL routing relationship, and later you can generate the URL you want based on this name

Urls.py:url (R ' ^url_1/', Views.index, name= ' i1 '), url (r ' ^url_2/(\d+)/(\d+)/', Views.index, name= ' i2 '), url (r ' ^url_3/( ? p<pid>\d+)/(? p<nid>\d+)/', Views.index, name= ' i3 '), Views.py:from django.urls import reversedef func (Request, *args, **kwargs) :    url1 = reverse (' i1 ')                              # url_1/    url2 = reverse (' I2 ', args= ())                 # url_2/1/2/    url3 = reverse (' i3 ', kwargs={' pid ': 1, "Nid": 9}) # url_3/1/9/xxx.html:        {% url "i1"%}               # url_1/    {% url "i2" 1 2%}           # url_2/1/2/    {% url "i3" pid=1 nid=9%}   # Url_3/1/9/ps:    # Displays the current URL    

4. Multi-level routing:

Multi-level routing to avoid collisions with multiple apps when the route (URL) in Project urls.py is consistent with the path name

#project/urls.py: From    django.conf.urls import URL, include from    django.contrib import admin    urlpatterns = [        URL (R ' ^app1/', include ("App1.urls")),        URL (r ' ^app2/', include ("App2.urls")),    ] #app01/urls.py:    From django.conf.urls import URL from    app1 import views    urlpatterns = [        url (R ' ^test ', views.test),    ]# app02/urls.py: From    django.conf.urls import URL from    app2 to import views    urlpatterns = [        url (r ' ^test ', views.test),    ]

5. Default value, Namespace

Pass

  

  

Second, the View

1, FBV&CBV

1.1. FBV (function Base view) writes logic based on functions in view

#urls. Py:url (R ' ^test ', views.test),  # FBV  function Base view#views.py:def Test (Request):    if Request.method = = "GET":        return render (Request, ' test.html ')

1.2, CBV (class Base Viev) in the View (view) based on the class writing logic

#urls. Py;url (R ' ^home ', views. Test.as_view ()),  # CBV  class Base View   . As_view () test has no view so inherit the Django view#views.py in the views.py test class: From django.views import Viewclass Test (View):    # Call the Dispatch method in the parent class and rewrite the    def dispatch (self, request, *args, * * Kwargs):  # through dispatch reflection can be found such as: Get, the starting point of the Post method        print ("before")        result = Super (Test, self). Dispatch ( Request, *args, **kwargs)        return result    def get (self, request):        print (Request.method)        return Render (Request, "home.html")    def post (self, request):        print (Request.method)        return render (Request, " Home.html ")

2. Example of extracting HTML from form submission data:

<!DOCTYPE HTML><HTMLLang= "en"><Head>    <MetaCharSet= "UTF-8">    <title>Title</title></Head><Body>    <formAction= "/test"Method= "POST"enctype= "Multipart/form-data"><!--Enctypes Property does not, the default commit is a string, unable to implement file upload -        <P>            <inputtype= "text"name= "User"placeholder= "User name" />        </P>        <P>            <inputtype= "Password"name= "pwd"placeholder= "Password" />        </P>        <P>Male:<inputtype= "Radio"name= "Gender"value= "1"/>female:<inputtype= "Radio"name= "Gender"value= "2"/>Publicity:<inputtype= "Radio"name= "Gender"value= "3"/>        </P>        <P>Male:<inputtype= "checkbox"name= "Favor"value= "One"/>female:<inputtype= "checkbox"name= "Favor"value= "All"/>Publicity:<inputtype= "checkbox"name= "Favor"value= " the"/>        </P>        <P>            <Selectname= "City"multiple>                <optionvalue= "sh">Shanghai</option>                <optionvalue= "BJ">Beijing</option>                <optionvalue= "TJ">Tianjin</option>            </Select>        </P>        <P>            <inputtype= "File"name= "File"/>        </P>        <inputtype= "Submit"value= "Submit"/>    </form></Body></HTML>
test.html
def Test (Request): if Request.method = = "GET": Return render (Request, ' Te St.html ') elif Request.method = = "POST": # text V = Request. Post.get (' pwd ') # Gets the input input box with the value print (v) # Radio V0 = Request. Post.get (' Gender ') # gets radio's value print (v0) # checkbox v1 = Request. Post.getlist (' favor ') # Gets the checkbox multiple selection in the case of value print (v1) # Select v2 = Request. Post.getlist (' city ') # Gets the Select drop-down box multiple case of Value print (v2) # File obj = Request. Files.get (' file ') # Gets the upload file and saves print (obj, type (obj), obj.name) import os file_path = Os.path.join (' Upload ', obj.name) F = open (File_path, mode= "WB") for I in Obj.chunks (): # chunks () use the generator to load only partially uploaded files at a time until the load is complete        Bi f.write (i) f.close () return redirect ("/test") Else: # put,delete,head,option ... Return Redirect ("/test") 

  

Third, the template

A rough overview of the previous blog post

Pass

  

"Python"--Django Routing system (URL relationship mapping), views, templates

Related Article

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.