Search This Blog

Editing Views - FormView - Python

 

Editing Views - FormView

A FormView based view displays a form which

  • on an error, redisplays the form with validation errors
  • on success, redirects to a new URL. Consider a sample form created in forms.py that defines a CharField for capturing name
from django import forms

class ContactForm(forms.Form):
    name = forms.CharField()

    def send_email(self):
        # code to send email
        pass

A view can be defined using this form as shown. This determines if a form is valid and takes appropriate action (calling send_email in the below case).

class ContactView(FormView):
    template_name = 'contact.html'
    form_class = ContactForm
    success_url = '/thanks/'

    def form_valid(self, form):
        # Call this method when valid form data has been POSTed.
        form.send_email()
        return super().form_valid(form)

No comments:

Post a Comment

If you have any doubts, Please let us know.