如何在基于Django类的视图中获取表单的提交值? [英] How to get the submitted value of a form in a Django class-based view?

查看:104
本文介绍了如何在基于Django类的视图中获取表单的提交值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Django form that looks like this:

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

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

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.

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)


推荐答案

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

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.

示例:

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)

这篇关于如何在基于Django类的视图中获取表单的提交值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆