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

标签 django post request

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

当我们编写 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/

相关文章:

javascript - 如何在 Django 中使用 css 和 javascript 的静态文件夹?

python - Django1.2/google-appengine 调试 "KeyError: ' REQUEST_METHOD“错误

python - 在 Django 中搜索 URL 有困难

php - CodeIgniter 闪存数据

python - 在线程中更改 Python 的 "requests"模块的连接池大小

python - GetStream (Django) - 无法丰富通知提要

c - 发送带有 XML 内容的 POST http 请求

javascript - 我们如何使用meteor restivus发布数据

error-handling - 处理基于 Redux 的应用程序中的请求错误

go - 下载前验证请求