18

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)
Saqib Ali
  • 11,931
  • 41
  • 133
  • 272

2 Answers2

24

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)
djvg
  • 11,722
  • 5
  • 72
  • 103
Alex
  • 8,321
  • 1
  • 34
  • 30
  • 1
    what if the form contains a many to many field? How do you retrieve all values submitted in class based views? – Abishek Jan 31 '20 at 13:22
  • My model generated a randomly generated slug. I need to retrieve this slug so the user can see the URL to the item created via an Email. How can I do this? – Surveyor Jr May 23 '22 at 12:17
3

try this:

 form.cleaned_data.get('email')
slim_chebbi
  • 798
  • 6
  • 9