【问题标题】:what exactly does django request.POST do and how to use it?django request.POST 究竟做了什么以及如何使用它?
【发布时间】:2013-07-28 13:38:08
【问题描述】:

我开始学习 django 并开始观看有关如何创建表单的教程,我已经看到很多地方都是这样创建表单的。

def create(request):
    if request.POST:
        form = ArticleForm(request.POST)
        if form.is_valid:
            form.save()
   else:
       form = ArticleForm()
   args = {}
   args.update(csrf(request))
   args['form'] = form
   return render_to_response('create_article.html', args)

现在,假设我创建了一个名为 Article 的模型,然后从该模型创建了一个 ArticleForm,那么这里到底发生了什么(在我上面提供的代码中)?我理解 if form.is_valid: form.save() 部分,根据我的阅读,request 应该始终是第一个参数,但是有人可以解释一下 request 作为参数的作用以及函数的前两行是什么正在做? else 语句和 else 语句(args 部分)之后到底发生了什么?

编辑:另外,假设 Article 模型有一个名为 name = models.CharField(max_length=20) 的字段,我有没有办法获取/访问用户为表单的特定部分输入的内容?假设我想获取名称并查看该名称是否已存在于我的数据库中,是否有办法让我这样做?

【问题讨论】:

    标签: django request


    【解决方案1】:

    request.POST 以及其他内容(例如 CSRF 令牌值)包含用户在表单中输入的所有数据。

    if request.POST
    

    检查用户是否确实验证了表单,否则请求中没有 POST 数据。

    form = ArticleForm(request.POST)
    

    起初看起来很奇怪,但是当用户验证表单时,会加载相同的页面,但 POST 数据在 django 表单中处理以进行数据验证(例如检查必填字段是否留空等),以便在表格中显示错误。 如果没有错误(form.is_valid()),则视图程序继续。

    【讨论】:

    • 嗯,好吧,假设 Article 模型有一个名为 name = models.CharField(max_length=20) 的字段,我有没有办法获取/访问用户为该特定部分输入的内容表格?假设我想获取名称并查看该名称是否已存在于我的数据库中,有没有办法让我这样做?
    • 绝对是的,代替“form.save()”,您可以获得每个字段数据(由表单 btw 清理)并单独处理它们,而无需将它们保存在数据库中。我没有使用我的 django 开发计算机,我忘记了执行此操作的确切语法……
    • 例如可能是 « specificFieldName = form.cleaned_data['particularFieldName'] »。
    【解决方案2】:

    希望您熟悉HTTP methods,例如 GET 和 POST。

    request 对象代表任何用户代理的单个请求。因此,它可以是您在浏览特定页面时从浏览器发送的请求,也可以是来自搜索引擎的爬虫发送的请求。阅读更多关于请求here

    request.POST 是这个request 对象的一个​​属性,它是一个QueryDict(非常类似于普通的Python dict)。它包含发送到您的视图的 HTTP POST 参数。

    简而言之,在您的示例中:

    def create(request):
        if request.POST:  # check if the request is POST request and it contains any parameter  
            form = ArticleForm(request.POST)  # then pass all those parameters to the form
            if form.is_valid:  # process the form to check if it's valid
                form.save()  # save the data if it's valid
            else:
                form = ArticleForm()  # if not valid data, initialize an new / empty form
        args = {}  # create a dict to pass to the template
        args.update(csrf(request))  # add the CSRF token
        args['form'] = form  # add the 'form' above to the 'args' dict
        return render_to_response('create_article.html', args)  # pass that dict to template
    

    不太清楚你为什么有这个例子,通常我会像这样做最后一部分:

    def create(request):
        .... your code ....
        else:
            form = ArticleForm()
        return render(request, 'create_article.html', { form: form })
    

    希望对你有帮助。

    【讨论】:

    • 是的,完美,我刚刚意识到你所做的要好得多.. 好吧,最后一个问题是,假设 Article 模型有一个名为 name = models.CharField(max_length=20 ),我有没有办法获取/访问用户为表单的特定部分输入的内容?假设我想获取名称并查看该名称是否已存在于我的数据库中,我该怎么做?
    • 是的,您可以使用request.POST.get('name', '') 或在您的表单中查看更早的视图,使用更简洁的表单。
    【解决方案3】:

    代码中有一些错误,似乎是从 SO 问题中复制粘贴的。我建议通过the excellent Django documentation,尤其是Django tutorial

    您的示例应该看起来像 this example from the Django docs

    这里有一些cmets:

    def create(request):
        if request.POST:
            form = ArticleForm(request.POST)
            if form.is_valid:
                form.save()
                # after successful POST
                # we want to redirect to a different page here
       else:
           form = ArticleForm()
       args = {}
       # you really don't need the following necessarily
       # just use `{% csrf_token %}` inside the form in your template
       args.update(csrf(request))
       args['form'] = form
       # using just `render` like in the example linked to above is more modern
       return render_to_response('create_article.html', args)
    

    【讨论】:

    • 好的,非常感谢!所以假设 Article 模型有一个名为 name = models.CharField(max_length=20) 的字段,我有没有办法获取/访问用户为表单的特定部分输入的内容?假设我想获取名称并查看该名称是否已存在于我的数据库中,我该怎么做?
    • 是的,当然。不要混淆 Django 表单和模型,它们有不同的意图(表单=用户输入验证,模型=数据持久性和访问)。试试 Django 教程或文档的模型/表单部分。
    猜你喜欢
    • 2021-11-12
    • 2012-07-14
    • 2011-05-03
    • 2020-07-29
    • 2012-07-23
    • 2016-09-10
    相关资源
    最近更新 更多