本文介绍了request.method =="POST"的作用是什么?在Django中意味着什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在自己的观点中使用了很多东西,但是我想知道这到底是什么意思.

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"?

推荐答案

如果来自用户的当前请求是使用HTTP的"POST"方法执行的,则request.method == "POST"的结果为布尔值-True c4>否则(通常意味着HTTP"GET",但还有其他方法).

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请求通常用于表单提交-如果处理表单会更改服务器端状态(例如,在注册表单的情况下,将用户添加到数据库),则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 Forms库:


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中意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 11:29