【问题标题】:Django and the form_valid methodDjango 和 form_valid 方法
【发布时间】:2019-03-10 21:23:25
【问题描述】:

我正在关注有关用户身份验证和授权的 Django 课程。但关键是我这里的form_valid()方法不是很懂:

class ArticleCreateView(CreateView):
    model = Article
    template_name = 'article_new.html'
    fields = ('title', 'body') # new

    def form_valid(self, form): # new
        form.instance.author = self.request.user
        return super().form_valid(form)

我不知道这个方法返回什么。

谢谢

【问题讨论】:

  • 它返回的是该方法的超类实现的结果,恰好是对成功URL的重定向。但是返回值并不是这里有趣的地方:课程是教你如何自动设置作者。
  • @DanielRoseman 感谢您的回复!我知道它在做什么,但我无法弄清楚幕后发生了什么

标签: python django forms django-class-based-views


【解决方案1】:

当在表单中输入正确的数据并且表单已成功验证且没有任何错误时,将调用此方法。您可以在此处处理成功后逻辑,例如向用户发送通知电子邮件、重定向到感谢页面等。

Django Documentation | Generic editing views

【讨论】:

    【解决方案2】:

    感谢回答这个问题的人。

    顺便说一下,这个例子来自本书:Django for Beginners 3.1 William S. Vincent

    用 Python 和 Django 构建网站

    我也想知道这种方法发生了什么。所以,我打印了 变量。

    print(f"form type: {type(form)}")
    

    结果:

    form type: <class 'django.forms.widgets.ArticleForm'>
    

    以下;是的,这确实是我填写的表格内容。

    print(f"form: {form}")
    
    form: 
    <tr>
      <th>
        <label for="id_title">Title:</label>
      </th>
      <td>
        <input type="text" name="title" value="This is the title for this article" maxlength="255" required id="id_title">
      </td>
    </tr>
    <tr>
      <th>
        <label for="id_body">Body:</label>
      </th>
      <td>
        <textarea name="body" cols="40" rows="10" required id="id_body">And, this is the contents of this article,...blah, blah, blah.</textarea>
      </td>
    </tr>
    

    在这里,我们将用户重定向到特定于这篇新创建的文章的页面。在此示例中,文章是已创建的第 8 篇文章。 status_code=302 是一个 URL 重定向

    print(f"response type: {type(response)}")
    print(f"response: {response}")
    

    结果如下:

    response type: <class 'django.http.response.HttpResponseRedirect'>
    response: <HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/articles/8/">
    

    当我查看重定向页面上的结果时,我可以看到确实为 author 分配了当前用户的值。因此,此方法负责将当前用户分配给作者字段。在表单中输入数据时无需让用户填写。

    如果您访问 GitHub django/django 并在此存储库中搜索 form_valid,以下链接将包含有关如何使用 form_valid 的各种示例。

    https://github.com/django/django/search?p=1&q=form_valid

    【讨论】:

      猜你喜欢
      • 2013-05-12
      • 2021-09-22
      • 2018-12-12
      • 1970-01-01
      • 2015-11-21
      • 2019-08-29
      • 1970-01-01
      • 2015-10-18
      • 2018-04-07
      相关资源
      最近更新 更多