gpt4 book ai didi

django - request.method == "POST"在 Django 中意味着什么?

转载 作者:行者123 更新时间:2023-12-02 09:50:55 32 4
gpt4 key购买 nike

我在我的观点中经常使用这个东西,但我想知道这到底意味着什么。

当我们编写 request.method == "GET"request.method == "POST" 时会发生什么?

最佳答案

如果用户当前请求是使用 HTTP“POST”方法执行的,request.method == "POST" 的结果是一个 bool 值 - True , False 否则(通常表示 HTTP“GET”,但也有其他方法)。

您可以阅读有关 GET 和 POST 之间差异的更多信息 in answers to the question Alasadir pointed you to 。简而言之,POST 请求通常用于表单提交 - 如果处理表单会更改服务器端状态(例如,在注册表单的情况下将用户添加到数据库),则需要它们。 GET 用于普通的 HTTP 请求(例如,当您只需在浏览器中键入 URL 时)以及可以在没有任何副作用的情况下处理的表单(例如搜索表单)。

该代码通常用在条件语句中,以区分用于处理提交表单的代码和用于显示未绑定(bind)表单的代码:

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.
<小时/>

这是另一个例子,taken straight from Django documentation ,使用 Django Forms 库:

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,
})

关于django - request.method == "POST"在 Django 中意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19132210/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com