Form processing with class-based views

We can essentially process a form by subclassing the View class itself:

class ClassBasedFormView(generic.View): 
    template_name = 'form.html' 
 
    def get(self, request): 
        form = PersonDetailsForm() 
        return render(request, self.template_name, {'form': form}) 
 
    def post(self, request): 
        form = PersonDetailsForm(request.POST) 
        if form.is_valid(): 
            # Success! We can use form.cleaned_data now 
            return redirect('success') 
        else: 
            # Invalid form! Reshow the form with error highlighted 
            return render(request, self.template_name, 
                          {'form': form}) 

Compare this code with the sequence diagram that we saw previously. The three scenarios have been separately handled.

Every form is expected to follow the post/redirect/get (PRG) pattern. ...

Get Django Design Patterns and Best Practices - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.