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

末鹿安然 提交于 2019-12-09 14:38:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!