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

时间:2022-03-02 20:21:22

I have a Django form that looks like this:

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

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

I have a an associated Class-Based FormView as shown below. I can see that the form is succesfully validating the data and flow is getting into the form_valid() method below. What I need to know is how to get the value that the user submitted in the email field. form.fields['email'].value doesn't work.

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

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)

2 个解决方案

#1


13  

You can check the form's cleaned_data attribute, which will be a dictionary with your fields as keys and values as values. Docs here.

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

Example:

例子:

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


1  

try this:

试试这个:

 form.cleaned_data.get('email')

#1


13  

You can check the form's cleaned_data attribute, which will be a dictionary with your fields as keys and values as values. Docs here.

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

Example:

例子:

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


1  

try this:

试试这个:

 form.cleaned_data.get('email')