问题
I have a Django form that looks like this:
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.
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)
回答1:
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.
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:
try this:
form.cleaned_data.get('email')
来源:https://stackoverflow.com/questions/25090003/how-to-get-the-submitted-value-of-a-form-in-a-django-class-based-view