问题描述
我在我的视图中经常使用这个东西,但我想知道这到底是什么意思.
I am using this thing in my views quite a lot but I want to know what exactly does that mean.
当我们编写 request.method == "GET"
或 request.method == "POST"
时会发生什么?
What happens when we write request.method == "GET"
or request.method == "POST"
?
推荐答案
request.method == "POST"
的结果是一个布尔值 - True
如果来自用户的当前请求是使用 HTTPPOST"方法执行的,否则为 False
(通常这意味着 HTTPGET",但也有其他方法).
The result of request.method == "POST"
is a boolean value - True
if the current request from a user was performed using the HTTP "POST" method, of False
otherwise (usually that means HTTP "GET", but there are also other methods).
您可以阅读有关 GET 和 POST 区别的更多信息在回答中Alasadir 向您指出的问题.简而言之,POST 请求通常用于表单提交 - 如果处理表单会更改服务器端状态(例如,在注册表的情况下将用户添加到数据库),则需要它们.GET 用于普通的 HTTP 请求(例如,当您只在浏览器中输入 URL 时)以及可以处理而没有任何副作用的表单(例如搜索表单).
You can read more about difference between GET and POST in answers to the question Alasadir pointed you to. In a nutshell POST requests are usually used for form submissions - they are required if processing a form would change server-side state (for example add user to a database, in case of a registration form). GET is used for normal HTTP requests (for example when you just type an URL into your browser) and for forms that can be processed without any side-effects (for example a search form).
该代码通常用于条件语句中,以区分处理提交表单的代码和显示未绑定表单的代码:
The code is usually used in conditional statements, to distinguish between code for processing a submitted form, and code for displaying an unbound form:
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 文档,使用 Django 表单库:
And here is another example, taken straight from Django documentation, using Django Forms library:
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,
})
这篇关于request.method == "POST" 是什么意思?在 Django 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!