如何在基于 Django 类的视图中获取表单的提交值? [英] How to get the submitted value of a form in a Django class-based view?
问题描述
我有一个像这样的 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屋!