【问题标题】:How to get the submitted value of a form in a Django class-based view?如何在基于 Django 类的视图中获取表单的提交值?
【发布时间】:2014-09-25 05:37:03
【问题描述】:

我有一个如下所示的 Django 表单:

class myForm(forms.Form):
    email = forms.EmailField(
        label="Email",
        max_length=254,
        required=True,
    )

我有一个关联的基于类的 FormView,如下所示。我可以看到表单已成功验证数据,并且流程正在进入下面的 form_valid() 方法。我需要知道的是如何获取用户在电子邮件字段中提交的值。 form.fields['email'].value 不起作用。

class myFormView(FormView):
    template_name = 'myTemplate.html'
    form_class = myForm
    success_url = "/blahblahblah"


    def form_valid(self, form):
        # How Do I get the submitted values of the form fields here?
        # I would like to do a log.debug() of the email address?
        return super(myFormView, self).form_valid(form)

【问题讨论】:

    标签: django django-forms django-views


    【解决方案1】:

    您可以检查表单的cleaned_data 属性,该属性将是一个字典,其中您的字段作为键,值作为值。文档here

    例子:

    class myFormView(FormView):
        template_name = 'myTemplate.html'
        form_class = myForm
        success_url = "/blahblahblah"
    
    
        def form_valid(self, form):
            email = form.cleaned_data['email']  # <--- Add this line to get email value
            return super(myFormView, self).form_valid(form)
    

    【讨论】:

    • 如果表单包含多对多字段怎么办?您如何检索在基于类的视图中提交的所有值?
    【解决方案2】:

    试试这个:

     form.cleaned_data.get('email')
    

    【讨论】:

      猜你喜欢
      • 2016-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-02
      • 2021-09-27
      • 2019-06-06
      • 1970-01-01
      • 2016-12-05
      相关资源
      最近更新 更多