如何在Django基于类的视图中获取表单的提交值?

Saq*_*Ali 13 django django-forms django-views

我有一个看起来像这样的Django表单:

class myForm(forms.Form):
    email = forms.EmailField(
        label="Email",
        max_length=254,
        required=True,
    )
Run Code Online (Sandbox Code Playgroud)

我有一个关联的基于类的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)
Run Code Online (Sandbox Code Playgroud)

Ale*_*lex 15

您可以检查表单的cleaned_data属性,该属性将是一个字段,其中您的字段为键,值为值.文档在这里.

例:

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)
Run Code Online (Sandbox Code Playgroud)