Form handling with class-based views

Form processing generally has 3 paths:

  • Initial GET (blank or prepopulated form)
  • POST with invalid data (typically redisplay form with errors)
  • POST with valid data (process the data and typically redirect)
    Implementing this yourself often results in a lot of repeated boilerplate code(see Using a form in a view). To help avoidthis, Django provides a collection of generic class-based views for formprocessing.

Basic forms

Given a simple contact form:

forms.py

  1. from django import forms
  2.  
  3. class ContactForm(forms.Form):
  4. name = forms.CharField()
  5. message = forms.CharField(widget=forms.Textarea)
  6.  
  7. def send_email(self):
  8. # send email using the self.cleaned_data dictionary
  9. pass

The view can be constructed using a FormView:

views.py

  1. from myapp.forms import ContactForm
  2. from django.views.generic.edit import FormView
  3.  
  4. class ContactView(FormView):
  5. template_name = 'contact.html'
  6. form_class = ContactForm
  7. success_url = '/thanks/'
  8.  
  9. def form_valid(self, form):
  10. # This method is called when valid form data has been POSTed.
  11. # It should return an HttpResponse.
  12. form.send_email()
  13. return super().form_valid(form)

注意:

Model forms

Generic views really shine when working with models. These genericviews will automatically create a ModelForm, so long asthey can work out which model class to use:

  • If the model attribute isgiven, that model class will be used.
  • If get_object()returns an object, the class of that object will be used.
  • If a queryset isgiven, the model for that queryset will be used.
    Model form views provide aform_valid() implementationthat saves the model automatically. You can override this if you have anyspecial requirements; see below for examples.

You don't even need to provide a success_url forCreateView orUpdateView - they will useget_absolute_url() on the model object if available.

If you want to use a custom ModelForm (for instance toadd extra validation) simply setform_class on your view.

注解

When specifying a custom form class, you must still specify the model,even though the form_class maybe a ModelForm.

First we need to add get_absolute_url() to ourAuthor class:

models.py

  1. from django.db import models
  2. from django.urls import reverse
  3.  
  4. class Author(models.Model):
  5. name = models.CharField(max_length=200)
  6.  
  7. def get_absolute_url(self):
  8. return reverse('author-detail', kwargs={'pk': self.pk})

Then we can use CreateView and friends to do the actualwork. Notice how we're just configuring the generic class-based viewshere; we don't have to write any logic ourselves:

views.py

  1. from django.urls import reverse_lazy
  2. from django.views.generic.edit import CreateView, DeleteView, UpdateView
  3. from myapp.models import Author
  4.  
  5. class AuthorCreate(CreateView):
  6. model = Author
  7. fields = ['name']
  8.  
  9. class AuthorUpdate(UpdateView):
  10. model = Author
  11. fields = ['name']
  12.  
  13. class AuthorDelete(DeleteView):
  14. model = Author
  15. success_url = reverse_lazy('author-list')

注解

We have to use reverse_lazy() here, not justreverse() as the urls are not loaded when the file is imported.

The fields attribute works the same way as the fields attribute on theinner Meta class on ModelForm. Unless you define theform class in another way, the attribute is required and the view will raisean ImproperlyConfigured exception if it's not.

If you specify both the fieldsand form_class attributes, anImproperlyConfigured exception will be raised.

Finally, we hook these new views into the URLconf:

urls.py

  1. from django.urls import path
  2. from myapp.views import AuthorCreate, AuthorDelete, AuthorUpdate
  3.  
  4. urlpatterns = [
  5. # ...
  6. path('author/add/', AuthorCreate.as_view(), name='author-add'),
  7. path('author/<int:pk>/', AuthorUpdate.as_view(), name='author-update'),
  8. path('author/<int:pk>/delete/', AuthorDelete.as_view(), name='author-delete'),
  9. ]

注解

These views inheritSingleObjectTemplateResponseMixinwhich usestemplate_name_suffixto construct thetemplate_namebased on the model.

In this example:

Models and request.user

To track the user that created an object using a CreateView,you can use a custom ModelForm to do this. First, addthe foreign key relation to the model:

models.py

  1. from django.contrib.auth.models import User
  2. from django.db import models
  3.  
  4. class Author(models.Model):
  5. name = models.CharField(max_length=200)
  6. created_by = models.ForeignKey(User, on_delete=models.CASCADE)
  7.  
  8. # ...

In the view, ensure that you don't include created_by in the list of fieldsto edit, and overrideform_valid() to add the user:

views.py

  1. from django.contrib.auth.mixins import LoginRequiredMixin
  2. from django.views.generic.edit import CreateView
  3. from myapp.models import Author
  4.  
  5. class AuthorCreate(LoginRequiredMixin, CreateView):
  6. model = Author
  7. fields = ['name']
  8.  
  9. def form_valid(self, form):
  10. form.instance.created_by = self.request.user
  11. return super().form_valid(form)

LoginRequiredMixin prevents users whoaren't logged in from accessing the form. If you omit that, you'll need tohandle unauthorized users in form_valid().

AJAX example

Here is a simple example showing how you might go about implementing a form thatworks for AJAX requests as well as 'normal' form POSTs:

  1. from django.http import JsonResponse
  2. from django.views.generic.edit import CreateView
  3. from myapp.models import Author
  4.  
  5. class AjaxableResponseMixin:
  6. """
  7. Mixin to add AJAX support to a form.
  8. Must be used with an object-based FormView (e.g. CreateView)
  9. """
  10. def form_invalid(self, form):
  11. response = super().form_invalid(form)
  12. if self.request.is_ajax():
  13. return JsonResponse(form.errors, status=400)
  14. else:
  15. return response
  16.  
  17. def form_valid(self, form):
  18. # We make sure to call the parent's form_valid() method because
  19. # it might do some processing (in the case of CreateView, it will
  20. # call form.save() for example).
  21. response = super().form_valid(form)
  22. if self.request.is_ajax():
  23. data = {
  24. 'pk': self.object.pk,
  25. }
  26. return JsonResponse(data)
  27. else:
  28. return response
  29.  
  30. class AuthorCreate(AjaxableResponseMixin, CreateView):
  31. model = Author
  32. fields = ['name']