[Fixed]-Convert my def view to class based view

1👍

Since you have a view that displays a form and which redisplays the form with validation errors on error and redirects to a new URL on success, you can use FormView generic view.

Your FBV code converted to CBV:

from django.views.generic import FormView

class Contact(FormView):

    form_class = ContactForm  # Form class to be used
    template_name = 'contact/contact.html' # Template to be used
    success_url = '/'  # Redirect to this url when form is valid

    def form_valid(self, form):
        template = get_template('contact/contact_template.txt')
        context_dict = form.cleaned_data
        context_dict['form_content'] = form.cleaned_data['content'] 
        context = Context(context_dict)             
        content = template.render(context)

        email = EmailMessage(
                "New contact form submission",
                content,
                "www.inexistente.com" + '<support@inexistente.com>',
                ['mymail@gmail.com'],
                headers={'Reply-To': contact_email}
            )
        email.send()
        return super(Contact, self).form_valid(form)

Here,
form_class: defines the form class to be used.
template_name: defines the template to be used to display the form.
success_url: defines the url to be used when the form is valid.

You can put all the logic for the code to be executed when form is valid inside the form_valid() function. After performing all the operations, call the super() which redirects to the success_url defined in your class.

Also, when you are building context to be passed to the email template, you can use the form.cleaned_data dictionary. All the keys you have used to build the context dictionary is same as in the form’s cleaned_data dictionary except the form_content key. So, i have just used the form’s cleaned_data dictionary and added an extra key form_content in a context_dict dictionary which will be then used in the email template for rendering.

Leave a comment