Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the submitted value of a form in a Django class-based view?

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)
like image 223
Saqib Ali Avatar asked Aug 01 '14 23:08

Saqib Ali


People also ask

How can I get form data in Django?

Using Form in a View In Django, the request object passed as parameter to your view has an attribute called "method" where the type of the request is set, and all data passed via POST can be accessed via the request. POST dictionary. The view will display the result of the login form posted through the loggedin.

What is Form_class in Django?

Hi Christopher 'form_class' is used in Django Class Based to depict the Form to be used in a class based view. See example in the docs: https://docs.djangoproject.com/en/2.1/topics/class-based-views/generic-editing/

What is FormView Django?

FormView refers to a view (logic) to display and verify a Django Form. For example, a form to register users at Geeksforgeeks. Class-based views provide an alternative way to implement views as Python objects instead of functions.


1 Answers

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)
like image 165
Alex Avatar answered Sep 24 '22 15:09

Alex