我在我的观点中使用了这个东西但是我想知道究竟是什么意思?当我们写request.method ==“GET”或“POST”
时会发生什么答案 0 :(得分:25)
request.method == "POST"
的结果是布尔值 - True
如果来自用户的当前请求是使用HTTP“POST”方法执行的,则为False
(通常这意味着HTTP) “GET”,但也有其他方法)。
您可以阅读有关GET和POST in answers to the question Alasadir pointed you to之间差异的更多信息。简而言之,POST请求通常用于表单提交 - 如果处理表单会改变服务器端状态(例如,在注册表单的情况下将用户添加到数据库),则需要它们。 GET用于正常的HTTP请求(例如,当您在浏览器中键入URL时)以及可以在没有任何副作用的情况下处理的表单(例如搜索表单)。
代码通常用于条件语句,以区分处理提交表单的代码和显示未绑定表单的代码:
if request.method == "POST":
# HTTP Method POST. That means the form was submitted by a user
# and we can find her filled out answers using the request.POST QueryDict
else:
# Normal GET Request (most likely).
# We should probably display the form, so it can be filled
# out by the user and submitted.
这是另一个使用Django Forms库的示例taken straight from Django documentation:
from django.shortcuts import render
from django.http import HttpResponseRedirect
def contact(request):
if request.method == 'POST': # If the form has been submitted...
form = ContactForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = ContactForm() # An unbound form
return render(request, 'contact.html', {
'form': form,
})
答案 1 :(得分:10)
request.method
返回请求方法的类型GET,POST,PUT,DELETE
等。
返回后,你将它与你的字符串进行比较。
比较运算符始终提供布尔值(True or False
)。
有时我们需要根据请求的方法类型处理功能。
if request.method == "GET":
# functionality 1
elif request.method == "POST":
# functionality 2
elif request.method == "PUT":
# functionality 3
elif request.method == "DELETE":
# functionality 4
请求方法GET
数据与url一起传递。
for request方法POST
数据在body内传递。在安全方法方面,类型POST
是更好的方法。
答案 2 :(得分:-1)
book_id = Book.objects.get(id=id) 如果 request.method == 'POST':
book_save == BookForm(request.POST, request.FILES, instance=book_id)
if book_save.is_valid():
book_save.save()
else:
book_save = BookForm(instance=book_id)
y = {
'form':book_save,
}
return render(request, 'pages/update.html', y)