SoFunction
Updated on 2024-12-13

Common operations on request, response in django views

request

Getting json data from a post request

def hello(request):
 data = ()
 ...

The json format and some non-forms serialized formats can be used to get the data in the request body from the request.is_ajax() for ajax requests.

Get the base url based on the requested information (sometimes the service has more domains, or you need to splice the url information dynamically)

# url :8888/wxpay/qrcode2/16122010404238801544?name=lzz
request.get_host() # :8888
request.get_full_path() # u'/wxpay/qrcode2/16122010404238801544?name=lzz'

request.build_absolute_uri('/') # ':8888/'
request.build_absolute_uri('/hello') # ':8888/hello'
request.build_absolute_uri() # ':8888/wxpay/qrcode2/16122010404238801544?name=lzz'

 # u'/wxpay/qrcode2/16122010404238801544'
 # 'http'

Get information about the checked checkbox in the form, e.g., the name of the checkbox is checks.

var_list = ('checks')

Returns a list object, or [] if there is no ���️, or [] if there is no key in the form.

response

json format response 1.8 version has been provided in the JsonResponse, from import JsonResponse can be used, the lower version of django can refer to the source code to write one of their own, a few lines of code on the line. Setting cookies and header in response

def xxxxview(request):
 ....

 resp = HttpResponseRedirect('/account/portal/?token=%s' % es)
 resp.set_cookie("coofilter", es, max_age=300)
 resp['Erya-Net-Type'] = NET_TYPE
 resp['Erya-Auth-Host'] = AUTH_HOST
 resp['Erya-Auth-Port'] = AUTH_PORT
 resp['Erya-Auth-Uip'] = ip
 resp['Erya-Auth-Token'] = es
 return resp

session

how to use session, mainly get and set, and delete

def post_comment(request, new_comment):
 if ('has_commented', False):
 return HttpResponse("You've already commented.")
 c = (comment=new_comment)
 ()
 ['has_commented'] = True
 return HttpResponse('Thanks for your comment!')

def logout(request):
 try:
 del ['member_id']
 except KeyError:
 pass
 return HttpResponse("You're logged out.")

cookies

def login(request):
 response = HttpResponseRedirect('/url/to_your_home_page')
 response.set_cookie('cookie_name1', 'cookie_name1_value')
 response.set_cookie('cookie_name2', 'cookie_name2_value')
 return response

def logout(request):
 response = HttpResponseRedirect('/url/to_your_login')
 response.delete_cookie('cookie_name1')
 response.delete_cookie('cookie_name2')
 return response

# Get
coo = ('coofilter')
# cookies expiration time
hr.set_cookie('user_id', user_id, max_age=300)    

Above this article on django views request, response of the common operation details is what I share with you all, I hope to give you a reference, and I hope you support me more.