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. If the submitted form is found to be valid, then it must issue a redirect. This prevents duplicate form submissions.

However, this is not a very DRY code. The form class name and template_name attributes have been repeated. Using a generic class-based view such as FormView can reduce the redundancy of form processing. The following code will give you the same functionality as the previous one, and in fewer lines of code:

from django.urls import reverse_lazy 
 
class GenericFormView(generic.FormView): 
    template_name = 'form.html' 
    form_class = PersonDetailsForm 
    success_url = reverse_lazy("success") 

We need to use reverse_lazy in this case because the URL patterns are not loaded when the View file is imported.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.75.28