1. Routing System--urls
4. ORM Operation
A. url.py
/index/ -> func
B. views.py
def func (Request):
# Request: Include all request data
...
return HttpResponse (' string ') # Returns the string returned
render (request, ' index.html ', {'}) # return template content
Retrun redirect (' url ') # returns URL
C. Template language return
render (request, ' index.html ', {' li ': [11,22,33]})
{ % for item in li%} # template speech for loop
Three, Django view –views
1, access to a number of user data and file upload1. Get user request data
Request. Get # Gets the data request sent in the corresponding information
. Post # Gets the data request sent by post in the corresponding information
. Files # Get the file data that is sent in the corresponding information
PS: # Gets and post are sent from the back table, just getting information in the URL, POST information contained in the data, often: get: # Obtain data
POST: # Submit Data
2, checkbox and many other selected content
Request. Post.getlist () # get only one value, like a check box, a multiple-selection drop-down box, you need to use GetList to get
3, Upload files
# Upload files, form tags make special settings enctype= "Multipart/form-data"
obj = Request. Files.get (' Fafafa ') # Get uploaded file object
print (obj.name) # upload file name
f = open (Obj.name, mode= ' WB ') for
Item in Obj.chunks (): # chunks (): chunking, 1.1-point data (generator, iterator)
f.write (item)
F.close ()
Example: Users submit data, receive response data in the background, and process
Project name: Mysite,app Name: CMDB, create receiving user upload Data directory upload
mysite/urls.py
From django.contrib Import admin
the From CMDB import views
urlpatterns = [
url (R ' ^admin/', admin.site.urls) C3/>url (R ' ^login/', Views.login),
]
cmdb/views.py
From django.shortcuts import Render, Redirect,httpresponse
def login (Request):
if Request.method = = "Get": Return
render (request, ' reg.html ')
elif Request.method = = "POST":
# Redio Select box to get
Redio = Request. Post.get ("gender")
print (Value of the checkbox:, Redio)
# checkbox check box get
checkbox = Request. Post.getlist ("favor")
print (Value of check box, checkbox)
# get file data
obj = Request. Files.get ("Fafafa")
print (obj, type (obj), obj.name) # Print file information
import os
file_path = Os.path.join ( ' Upload ', obj.name) with
open (File_path, mode= "WB") as F: to
I in Obj.chunks ():
f.write (i)
return Render (Request, "reg.html")
else:
# put, DELETE, head, OPTION ...
Return Redirect ("/reg/")
Templates/reg.html
<body> <form action= "/login/" method= "POST" enctype= "Multipart/form-data" > <p> & Lt;input type= "text" name= "user" placeholder= "username"/> </p> <p> <input type= " Password "name=" pwd "placeholder= password"/> </p> <p> Sex: male: <input type= "Radio"
Name= "Gender" value= "1"/> female: <input type= "Radio" name= "Gender" value= "2"/> </p> <p> Hobbies: Male: <input type= "checkbox" Name= "favor" value= "one"/> female: <input type= "checkbox"
Name= "Favor" value= "<select"/> </p> <p> name= "City" multiple>
<option value= "sh" > Shanghai </option> <option value= "BJ" > Beijing </option>
<option value= "TJ" > Tianjin </option> </select> </p> <p> <input type= "File" Name= "Fafafa"/> </p> <input type= "Submit" value= "submitted"/> </form> </body>
2, FBV and CBV
Match login like this urls.py, followed by a function name. When the match succeeds, the function in views.py is executed, and the first parameter in the function encapsulates all user request information. Like this called FBV (function base view)
There's another one in Django:CBV (class base view)
/index/-> The name of the letter
/index/-> Class
The above are all FBV way, below see CBV writing:
urls.py
URL (r ' ^home/', views. Home.as_view ()), # CBV fixed usage
views.py
From django.views import View
class home view: # Custom classes must inherit View
# Override the Parent class dispatch method. The
dispatch method of the # parent class can be used to find the method of get, post and so on, which is realized based on reflection.
def dispatch (self, request, *args, **kwargs):
print ("Similar to adorner: before") Result
= Super (home,self). Dispatch ( Request, *args, **kwargs)
print ("Similar to adorner: after") return result
def get (self,request): # define Get method, Get request executes this method
print (Request.method) return
render (request, "home.html")
def Post (self,request): # define Post method, POST request to execute this method
print (Request.method, "POST method") return
render (request, "home.html")
Home.html
<body>
<form action= "/home/" method= "POST" >
<input type= "text" name= "user"/>
< Input type= "Submit"/>
</form>
</body>
3. Decoration Device
Next article Add Four, Django template supplement - Django Template language cycle dictionary
urls.py
URL (r ' ^index/', Views.index),
views.py
User_dict = {'
key1 ': {' name ': ' Root1 ', ' eamil ': ' root@126.com '},
' Key2 ': {' name ': ' Root2 ', ' eamil ': ' Root@126.com '},
' Key3 ': {' name ': ' root3 ', ' eamil ': ' root@126.com '},
def index (request): Return
Render (Request, ' index.html ', {' user_dict ': user_dict})
Index.html
<body>
{USER_DICT.K1}}
<ul>
{# for row in User_dict # The default loop shows the key #}
{% for k in U Ser_dict.keys%} {# Loop dictionary: Key Value #}
<li>{{k}}</li>
{% endfor%}
</ul>
<ul >
{% for Val in user_dict.values%} {# Loop dictionary: Take value #}
<li>{{val}}</li>
{% endfor%}
</ul>
<ul>
{% for k,row in user_dict.items%} {# Loop dictionary: Fetch key, Value #}
<li>{ {k}} -{{row}}</li>
{% endfor%}
</ul>
</body>
Five, Django routing system
1, one-to-one: a URL for a function or a class
URL (r ' ^index/', views.index),
url (r ' ^home/', views. Home.as_view ()),
2.1, One-to-many: A class of URLs corresponding to a function or a class
As shown on the loop dictionary, if the host information, should display the host name, click to display details. Implemented as follows:
urls.py
URL (r ' ^index/', views.index),
url (r ' ^detail-(key\d+). html/', Views.detail),
Note: The way URLs are implemented here are similar to http://127.0.0.1/detail-key1.html, not previous detail. Nid=key1 the way. this way, for the weight of the site, search engines prefer the first way. The weight is better, will let the search engine think the webpage is static.
views.py
User_dict = {'
key1 ': {' name ': ' Root1 ', ' eamil ': ' root@126.com '},
' Key2 ': {' name ': ' Root2 ', ' eamil ': ' Root@126.com '},
' Key3 ': {' name ': ' root3 ', ' eamil ': ' root@126.com '},
' Key4 ': {' name ': ' Root4 ', ' eamil ': ' Root@126.com '},
' Key5 ': {' name ': ' Root5 ', ' eamil ': ' root@126.com '},
def index (request): Return
Render (Request, ' index.html ', {' user_dict ': user_dict})
def detail (Request, nid):
# Nid:url two times filtered values obtained
detail_info = User_dict[nid] return
render (request, ' detail.html ', {' Detail_info ': Detail_info})
Index.html
<ul>
{% for k,row in user_dict.items%}
<li><a target= "_blank" href= "/detail-{{k}}.html" >{{ Row.name}}</a></li>
{% endfor%}
</ul>
Detail.html
<body>
2.2, a One-to-many, usage summaryIn the example above, two matches a value, and multiple parameters match:
Urls.py:url (R ' ^detail-(key\d+). html/', Views.detail),
Views.py:def detail (Request, nid):
Access URL: 127.0.0.1/detail-key1.html If you match one more value, you'll see the following:
Urls.py:url (R ' ^detail-(key\d+)-(\d+). html/', Views.detail),
Views.py:def detail (Request, NID, UID):
Visit URL: 127.0.0.1/detail-key1-9.html
visible: Two matching values in the URL, and the parameters must be one by one corresponding , but if the position is changed, the inside code will also be changed to support regular expression grouping
Urls.py:url (R ' ^detail-) (? p<nid>\d+)-(? p<uid>\d+). html/', Views.detail),
The Direct first match is passed to Nid, and the second match is passed to the UID, which is not related to the position of the function parameter in the views.
Views.py:def detail (Request, NID, UID):
Visit URL: 127.0.0.1/detail-key1-9.html Group, the number of uncertain *args,**kwargs can also be used
URL (r ' ^detail-(key\d+)-(\d+). html/', views.detail),--> def detail (Request, *args):
URL (r ' ^detail-(?) p<nid>\d+)-(? p<uid>\d+). html/', views.detail),--> def detail (Request, **kwargs): 3, name parameter
The following: The action= "/home/" in the submission form needs to be modified with the URL's web address.
Home.html
<form action= "/home/" method= "POST" >
<input type= "text" name= "user"/> <input "
submit"/ >
</form>
urls.py
URL (r ' ^home/', views.home),
This is true of other web frameworks, which need to be modified in both places. Here Django provides a convenient usage, the name parameter.
Name:django Simple Usage
Name the URL routing relationship, and then you can generate the URL you want based on this name
urls.py
URL (r ' ^home/', Views.home, name= "homeee"),
Home.html
<form action= "{% url ' homeee '%}" method= "POST" >
<input type= "text" name= "user"/> <input
"type=" Submit "/>
</form>
After this writing, the URL changed, only to modify the urls.py there one place on it. Name: Grouped processing in a matching address
The second type:
# urls.py
url (r ' ^yug/(\d+)/(\d+)/', Views.index, name= ' i2 '),
# views.py
def index (REQUEST,NID,UID):
......
# HTML
{% url "i2" 1 2} # successful match all, all jump to: yug/1/2/
The third type:
# urls.py
url (r ' ^buy/) (? p<pid>\d+)/(? p<nid>\d+)/', Views.index, name= ' i3 '), # buy/1/9/
# HTML
{% URL ' i3 ' pid=1 nid=9%} # buy/1/9/
The above is generated through the template speech URL, the following is generated through the Reverse module URL, two ways to achieve the same functionality.
# views.py file
def func (Request, *args, **kwargs):
from django.urls import Reverse # generates a url< based on the name inversion C15/>URL1 = reverse (' i1 ') # asdfasdfasdf/
url2 = reverse (' I2 ', args= (1,2,)) # yug/1/2/
url3 = Reverse (' i3 ', kwargs={' pid ': 1, "Nid": 9}) # buy/1/9/
function: After the user completes certain actions, jumps to the specified page.
# Note:
request.path_info # current URL
def index (request,nid):
print (Request.path_info) return
render (Request, ' index.html ')
<form action= "{Request.path_info}}" method= "POST" >
4. URL route distribution mechanism
The previous URLs are in urls.py, and if multiple apps need to be introduced here. If you have more than one app, any changes to the app will modify this URL file.
Within Django, there is a mechanism for distributing URLs.
urls.py
From django.conf.urls import include
urlpatterns = [
url (R ' ^monitor/', include ("App02.urls")),
]
app02/urls.py
From the Django.conf.urls import URL
from app02 import views
urlpatterns = [
url (R ' ^login/', views.login) c15/>]
Visit Http://127.0.0.1/monitor/login to access the APP02 login page. 5, default value 6. Name Space
Follow-up articles supplement
Reprint Please be sure