Method of submitting form and interacting with front and back end in Django
- 2021-07-22 10:23:35
- OfStack
META of Django interacts with front and back ends
1 Submit the GET of the form
Front-end data submission and transmission
1 ) Submit form data
2 ) Submit JSON Data
Back-end data reception and response
1 ) Receive GET Request data
2 ) Receive POST Request data
3 ) Respond to requests
GET Request process
Front-end through ajax Initiate GET Request ,json Format data
var data = {
"name": "test",
"age": 1
};
$.ajax({
type: 'GET',
url: /your/url/,
data: data, # Will eventually be converted into a query string followed by url Back: /your/url/?name=test&age=1
dataType: 'json', # Note: This refers to the server returning json Format data
success: function(data) { # Here's data Is json Format data
},
error: function(xhr, type) {
}
});
Back-end acceptance GET Request data
name = request.GET.get('name', '')
age = int(request.GET.get('age', '0'))
2 Submit form POST
Mode 1:
Front-end transmission POST Request :
var data = {}
# If the page does not have a form, it just input Box, and the request only sends these values, you can directly get the values put into the data Medium
data['name'] = $('#name').val()
# If the page has a form, you can use the jquery Adj. serialize() Method to get all the data of the form
data = $('#form1').serialize();
$.ajax({
type: 'POST',
url: /your/url/,
data: data, #request Header The default in the Content-Type:application/x-www-form-urlencoded
dataType: 'json', # Note: The type of data expected from the server
success: function(data) { # Here's data Is json Format data
},
error: function(xhr, type) {
}
});
Note : ajax Is not specified in content-type Type , The default in the request header is Content-Type:application/x-www-form-urlencoded, So the parameter is encoded as name=xx&age=1 Submit to backend , Back-end processing as form data
Back-end accepts request form data :
name = request.POST.get('name', '')
age = int(request.POST.get('age', '0'))
Mode 2:
Front-end through POST Submit JSON Data
# POST1 A json Data
var data = {
" name " : "test",
"age", 1
}
$.ajax({
type: 'POST',
url: /your/url/,
data: JSON.stringify(data), # json Object to a string
#request Header Indicate content-type:'application/json; charset=UTF-8'
contentType: 'application/json; charset=UTF-8',
dataType: 'json', # Note: Expect the server to return json Format data
success: function(data) { # Here's data Is json Format data
},
error: function(xhr, type) {
}
});
Note : If you want to pass to the backend json Data , You need to increase content-type Parameter, tells the back end, the data format passed in, and
And you need to set the data Convert to a string for passing. In fact, when the server receives it, it finds that it is json Format, the operation is to convert the string to json Object.
In addition, it is not converted to a string, even if it is added content-type Parameters of, will also be converted to by default name=xx&age=1 So that the backend cannot get the correct json .
Back-end accepts data :
data = request.get_json()
In addition, if the data format submitted by the front end cannot be recognized, you can use request.get_data() Receive data.
3 request. META composition
request.META Yes python Medium 1 A dictionary , Includes all of this time HTTP Requested Header Information , For example ip , browser
Agent . Attention Header The complete list of information depends on the information sent by the user Header Information and server-side settings header Information, common key-value pairs are :
(1) HTTP_USER_AGENT Of the user's browser user-agent String , For example: "Mozilla/5.0 (X11; U; Linux i686; fr-FR; rv:1.8.1.17) Gecko/20080829 Firefox/2.0.0.17" .
(2) REMOTE_ADDR Client ip Such as "12.345.67.89" If the application is going through a proxy server, it may be
Multiple divided by commas IP Address, such as: "12.345.67.89,23.456.78.90")
request.META Yes python1 Ordinary dictionaries, when the key does not exist, the access will be triggered 1 A KeyError Abnormal. 1 General adoption
try/execpt Statement or use python Medium get() Method to handle, set the default return, friendly response client.
4 request. META call design
( 1 ) To get user browser information , It can usually be written:
def ua_display(request):
info = request.META.get('HTTP_USER_AGENT', 'unknown')
return HttpResponse("Your browser is %s" % info)
(2) Adopt try/execpt Statement to prevent blocking programs
def ua_display_2(request):
try:
info = request.META['HTTP_USER_AGENT']
except KeyError:
info = 'unknown'
return HttpResponse("Your browser is %s" % info)
(3) Want to see META What are the specific data in, using python Dictionary gets key value items Method
values = request.META.items()
info = []
for k,v in values:
info.append('<tr><td>%s</td><td>%s</td></tr>' % (k, v))
(4)
CONTENT_LENGTH Text length
CONTENT_TYPE Data type
HTTP_ACCEPT_ENCODING Code
HTTP_ACCEPT_LANGUAGE Language
HTTP_REFERER Reference page , If there is one
HTTP_USER_AGENT Client User Agent String
QUERY_STRING Query string , Single 1 Unresolved string of
REMOTE_ADDR Client IP Address
REMOTE_HOST Client hostname
REQUEST_METHOD Request mode , For example GET Or POST
SERVER_NAME Server hostname
SERVER_PORT Server port
The information is as follows:
ALLUSERSPROFILE C:\ProgramData
COMMONPROGRAMFILES C:\Program Files\Common Files
COMSPEC C:\windows\system32\cmd.exe
CONFIGSETROOT C:\windows\ConfigSetRoot
CONTENT_LENGTH
CONTENT_TYPE text/plain
CSRF_COOKIE 8dLJLZyBH801ba24VdzYqJ81b5nqTxh0
DJANGO_SETTINGS_MODULE PythonProject.settings
FP_NO_HOST_CHECK NO
GATEWAY_INTERFACE CGI/1.1
HOMEDRIVE C:
HTTP_ACCEPT text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
HTTP_ACCEPT_ENCODING gzip,deflate,sdch
HTTP_ACCEPT_LANGUAGE zh-CN,zh;q=0.8
HTTP_CONNECTION keep-alive
HTTP_COOKIE csrftoken=8dLJLZyBH801ba24VdzYqJ81b5nqTxh0; sessionid=1rf6hmdw7k0zzsg8q3q1lw2j75gmoood
HTTP_HOST 127.0.0.1:8000
HTTP_USER_AGENT Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36
NUMBER_OF_PROCESSORS 4
OS Windows_NT
PATH E:\Python;E:\Python\Scripts;C:\windows\system32;E:\Python
PATHEXT .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
PATH_INFO /display_meta/
PROCESSOR_ARCHITECTURE AMD64
PROCESSOR_IDENTIFIER Intel64 Family 6 Model 42 Stepping 7, GenuineIntel
PROCESSOR_LEVEL 6
PROCESSOR_REVISION 2a07
PROMPT $P$G
PSMODULEPATH C:\windows\system32\WindowsPowerShell\v1.0\Modules\
PUBLIC C:\Users\Public
QUERY_STRING
REMOTE_ADDR 127.0.0.1
REMOTE_HOST
REQUEST_METHOD GET
RUN_MAIN true
SERVER_PROTOCOL HTTP/1.1
SERVER_SOFTWARE WSGIServer/0.1 Python/2.7.5
SESSIONNAME Console
SHIM_MCCOMPAT 0x810000001
WINDOWS_TRACING_FLAGS 3
WINDOWS_TRACING_LOGFILE C:\BVTBin\Tests\installpackage\csilogfile.log
wsgi.errors ', mode 'w' at 0x00000000025C6150>
wsgi.file_wrapper wsgiref.util.FileWrapper
wsgi.input
wsgi.multiprocess False
wsgi.multithread True
wsgi.run_once False
wsgi.url_scheme http
wsgi.version (1, 0)