| 1 |
==================================== |
| 2 |
Form handling with class-based views |
| 3 |
==================================== |
| 4 |
|
| 5 |
Form processing generally has 3 paths: |
| 6 |
|
| 7 |
* Initial GET (blank or prepopulated form) |
| 8 |
* POST with invalid data (typically redisplay form with errors) |
| 9 |
* POST with valid data (process the data and typically redirect) |
| 10 |
|
| 11 |
Implementing this yourself often results in a lot of repeated boilerplate code |
| 12 |
(see :ref:`Using a form in a view<using-a-form-in-a-view>`). To help avoid |
| 13 |
this, Django provides a collection of generic class-based views for form |
| 14 |
processing. |
| 15 |
|
| 16 |
Basic forms |
| 17 |
=========== |
| 18 |
|
| 19 |
Given a contact form: |
| 20 |
|
| 21 |
.. code-block:: python |
| 22 |
:caption: ``forms.py`` |
| 23 |
|
| 24 |
from django import forms |
| 25 |
|
| 26 |
|
| 27 |
class ContactForm(forms.Form): |
| 28 |
name = forms.CharField() |
| 29 |
message = forms.CharField(widget=forms.Textarea) |
| 30 |
|
| 31 |
def send_email(self): |
| 32 |
# send email using the self.cleaned_data dictionary |
| 33 |
pass |
| 34 |
|
| 35 |
The view can be constructed using a ``FormView``: |
| 36 |
|
| 37 |
.. code-block:: python |
| 38 |
:caption: ``views.py`` |
| 39 |
|
| 40 |
from myapp.forms import ContactForm |
| 41 |
from django.views.generic.edit import FormView |
| 42 |
|
| 43 |
|
| 44 |
class ContactFormView(FormView): |
| 45 |
template_name = "contact.html" |
| 46 |
form_class = ContactForm |
| 47 |
success_url = "/thanks/" |
| 48 |
|
| 49 |
def form_valid(self, form): |
| 50 |
# This method is called when valid form data has been POSTed. |
| 51 |
# It should return an HttpResponse. |
| 52 |
form.send_email() |
| 53 |
return super().form_valid(form) |
| 54 |
|
| 55 |
Notes: |
| 56 |
|
| 57 |
* FormView inherits |
| 58 |
:class:`~django.views.generic.base.TemplateResponseMixin` so |
| 59 |
:attr:`~django.views.generic.base.TemplateResponseMixin.template_name` |
| 60 |
can be used here. |
| 61 |
* The default implementation for |
| 62 |
:meth:`~django.views.generic.edit.FormMixin.form_valid` simply |
| 63 |
redirects to the :attr:`~django.views.generic.edit.FormMixin.success_url`. |
| 64 |
|
| 65 |
Model forms |
| 66 |
=========== |
| 67 |
|
| 68 |
Generic views really shine when working with models. These generic |
| 69 |
views will automatically create a :class:`~django.forms.ModelForm`, so long as |
| 70 |
they can work out which model class to use: |
| 71 |
|
| 72 |
* If the :attr:`~django.views.generic.edit.ModelFormMixin.model` attribute is |
| 73 |
given, that model class will be used. |
| 74 |
* If :meth:`~django.views.generic.detail.SingleObjectMixin.get_object()` |
| 75 |
returns an object, the class of that object will be used. |
| 76 |
* If a :attr:`~django.views.generic.detail.SingleObjectMixin.queryset` is |
| 77 |
given, the model for that queryset will be used. |
| 78 |
|
| 79 |
Model form views provide a |
| 80 |
:meth:`~django.views.generic.edit.ModelFormMixin.form_valid()` implementation |
| 81 |
that saves the model automatically. You can override this if you have any |
| 82 |
special requirements; see below for examples. |
| 83 |
|
| 84 |
You don't even need to provide a ``success_url`` for |
| 85 |
:class:`~django.views.generic.edit.CreateView` or |
| 86 |
:class:`~django.views.generic.edit.UpdateView` - they will use |
| 87 |
:meth:`~django.db.models.Model.get_absolute_url()` on the model object if available. |
| 88 |
|
| 89 |
If you want to use a custom :class:`~django.forms.ModelForm` (for instance to |
| 90 |
add extra validation), set |
| 91 |
:attr:`~django.views.generic.edit.FormMixin.form_class` on your view. |
| 92 |
|
| 93 |
.. note:: |
| 94 |
When specifying a custom form class, you must still specify the model, |
| 95 |
even though the :attr:`~django.views.generic.edit.FormMixin.form_class` may |
| 96 |
be a :class:`~django.forms.ModelForm`. |
| 97 |
|
| 98 |
First we need to add :meth:`~django.db.models.Model.get_absolute_url()` to our |
| 99 |
``Author`` class: |
| 100 |
|
| 101 |
.. code-block:: python |
| 102 |
:caption: ``models.py`` |
| 103 |
|
| 104 |
from django.db import models |
| 105 |
from django.urls import reverse |
| 106 |
|
| 107 |
|
| 108 |
class Author(models.Model): |
| 109 |
name = models.CharField(max_length=200) |
| 110 |
|
| 111 |
def get_absolute_url(self): |
| 112 |
return reverse("author-detail", kwargs={"pk": self.pk}) |
| 113 |
|
| 114 |
Then we can use :class:`CreateView` and friends to do the actual |
| 115 |
work. Notice how we're just configuring the generic class-based views |
| 116 |
here; we don't have to write any logic ourselves: |
| 117 |
|
| 118 |
.. code-block:: python |
| 119 |
:caption: ``views.py`` |
| 120 |
|
| 121 |
from django.urls import reverse_lazy |
| 122 |
from django.views.generic.edit import CreateView, DeleteView, UpdateView |
| 123 |
from myapp.models import Author |
| 124 |
|
| 125 |
|
| 126 |
class AuthorCreateView(CreateView): |
| 127 |
model = Author |
| 128 |
fields = ["name"] |
| 129 |
|
| 130 |
|
| 131 |
class AuthorUpdateView(UpdateView): |
| 132 |
model = Author |
| 133 |
fields = ["name"] |
| 134 |
|
| 135 |
|
| 136 |
class AuthorDeleteView(DeleteView): |
| 137 |
model = Author |
| 138 |
success_url = reverse_lazy("author-list") |
| 139 |
|
| 140 |
.. note:: |
| 141 |
We have to use :func:`~django.urls.reverse_lazy` instead of |
| 142 |
``reverse()``, as the urls are not loaded when the file is imported. |
| 143 |
|
| 144 |
The ``fields`` attribute works the same way as the ``fields`` attribute on the |
| 145 |
inner ``Meta`` class on :class:`~django.forms.ModelForm`. Unless you define the |
| 146 |
form class in another way, the attribute is required and the view will raise |
| 147 |
an :exc:`~django.core.exceptions.ImproperlyConfigured` exception if it's not. |
| 148 |
|
| 149 |
If you specify both the :attr:`~django.views.generic.edit.ModelFormMixin.fields` |
| 150 |
and :attr:`~django.views.generic.edit.FormMixin.form_class` attributes, an |
| 151 |
:exc:`~django.core.exceptions.ImproperlyConfigured` exception will be raised. |
| 152 |
|
| 153 |
Finally, we hook these new views into the URLconf: |
| 154 |
|
| 155 |
.. code-block:: python |
| 156 |
:caption: ``urls.py`` |
| 157 |
|
| 158 |
from django.urls import path |
| 159 |
from myapp.views import AuthorCreateView, AuthorDeleteView, AuthorUpdateView |
| 160 |
|
| 161 |
urlpatterns = [ |
| 162 |
# ... |
| 163 |
path("author/add/", AuthorCreateView.as_view(), name="author-add"), |
| 164 |
path("author/<int:pk>/", AuthorUpdateView.as_view(), name="author-update"), |
| 165 |
path("author/<int:pk>/delete/", AuthorDeleteView.as_view(), name="author-delete"), |
| 166 |
] |
| 167 |
|
| 168 |
.. note:: |
| 169 |
|
| 170 |
These views inherit |
| 171 |
:class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin` |
| 172 |
which uses |
| 173 |
:attr:`~django.views.generic.detail.SingleObjectTemplateResponseMixin.template_name_suffix` |
| 174 |
to construct the |
| 175 |
:attr:`~django.views.generic.base.TemplateResponseMixin.template_name` |
| 176 |
based on the model. |
| 177 |
|
| 178 |
In this example: |
| 179 |
|
| 180 |
* :class:`CreateView` and :class:`UpdateView` use ``myapp/author_form.html`` |
| 181 |
* :class:`DeleteView` uses ``myapp/author_confirm_delete.html`` |
| 182 |
|
| 183 |
If you wish to have separate templates for :class:`CreateView` and |
| 184 |
:class:`UpdateView`, you can set either |
| 185 |
:attr:`~django.views.generic.base.TemplateResponseMixin.template_name` or |
| 186 |
:attr:`~django.views.generic.detail.SingleObjectTemplateResponseMixin.template_name_suffix` |
| 187 |
on your view class. |
| 188 |
|
| 189 |
Models and ``request.user`` |
| 190 |
=========================== |
| 191 |
|
| 192 |
To track the user that created an object using a :class:`CreateView`, |
| 193 |
you can use a custom :class:`~django.forms.ModelForm` to do this. First, add |
| 194 |
the foreign key relation to the model: |
| 195 |
|
| 196 |
.. code-block:: python |
| 197 |
:caption: ``models.py`` |
| 198 |
|
| 199 |
from django.contrib.auth.models import User |
| 200 |
from django.db import models |
| 201 |
|
| 202 |
|
| 203 |
class Author(models.Model): |
| 204 |
name = models.CharField(max_length=200) |
| 205 |
created_by = models.ForeignKey(User, on_delete=models.CASCADE) |
| 206 |
|
| 207 |
# ... |
| 208 |
|
| 209 |
In the view, ensure that you don't include ``created_by`` in the list of fields |
| 210 |
to edit, and override |
| 211 |
:meth:`~django.views.generic.edit.ModelFormMixin.form_valid()` to add the user: |
| 212 |
|
| 213 |
.. code-block:: python |
| 214 |
:caption: ``views.py`` |
| 215 |
|
| 216 |
from django.contrib.auth.mixins import LoginRequiredMixin |
| 217 |
from django.views.generic.edit import CreateView |
| 218 |
from myapp.models import Author |
| 219 |
|
| 220 |
|
| 221 |
class AuthorCreateView(LoginRequiredMixin, CreateView): |
| 222 |
model = Author |
| 223 |
fields = ["name"] |
| 224 |
|
| 225 |
def form_valid(self, form): |
| 226 |
form.instance.created_by = self.request.user |
| 227 |
return super().form_valid(form) |
| 228 |
|
| 229 |
:class:`~django.contrib.auth.mixins.LoginRequiredMixin` prevents users who |
| 230 |
aren't logged in from accessing the form. If you omit that, you'll need to |
| 231 |
handle unauthorized users in :meth:`~.ModelFormMixin.form_valid()`. |
| 232 |
|
| 233 |
.. _content-negotiation-example: |
| 234 |
|
| 235 |
Content negotiation example |
| 236 |
=========================== |
| 237 |
|
| 238 |
Here is an example showing how you might go about implementing a form that |
| 239 |
works with an API-based workflow as well as 'normal' form POSTs:: |
| 240 |
|
| 241 |
from django.http import JsonResponse |
| 242 |
from django.views.generic.edit import CreateView |
| 243 |
from myapp.models import Author |
| 244 |
|
| 245 |
|
| 246 |
class JsonableResponseMixin: |
| 247 |
""" |
| 248 |
Mixin to add JSON support to a form. |
| 249 |
Must be used with an object-based FormView (e.g. CreateView) |
| 250 |
""" |
| 251 |
|
| 252 |
def form_invalid(self, form): |
| 253 |
response = super().form_invalid(form) |
| 254 |
if self.request.accepts("text/html"): |
| 255 |
return response |
| 256 |
else: |
| 257 |
return JsonResponse(form.errors, status=400) |
| 258 |
|
| 259 |
def form_valid(self, form): |
| 260 |
# We make sure to call the parent's form_valid() method because |
| 261 |
# it might do some processing (in the case of CreateView, it will |
| 262 |
# call form.save() for example). |
| 263 |
response = super().form_valid(form) |
| 264 |
if self.request.accepts("text/html"): |
| 265 |
return response |
| 266 |
else: |
| 267 |
data = { |
| 268 |
"pk": self.object.pk, |
| 269 |
} |
| 270 |
return JsonResponse(data) |
| 271 |
|
| 272 |
|
| 273 |
class AuthorCreateView(JsonableResponseMixin, CreateView): |
| 274 |
model = Author |
| 275 |
fields = ["name"] |
| 276 |
|
| 277 |
The above example assumes that if the client supports ``text/html``, that they |
| 278 |
would prefer it. However, this may not always be true. When requesting a |
| 279 |
``.css`` file, many browsers will send the header |
| 280 |
``Accept: text/css,*/*;q=0.1``, indicating that they would prefer CSS, but |
| 281 |
anything else is fine. This means ``request.accepts("text/html")`` will be |
| 282 |
``True``. |
| 283 |
|
| 284 |
To determine the correct format, taking into consideration the client's |
| 285 |
preference, use :func:`django.http.HttpRequest.get_preferred_type`:: |
| 286 |
|
| 287 |
class JsonableResponseMixin: |
| 288 |
""" |
| 289 |
Mixin to add JSON support to a form. |
| 290 |
Must be used with an object-based FormView (e.g. CreateView). |
| 291 |
""" |
| 292 |
|
| 293 |
accepted_media_types = ["text/html", "application/json"] |
| 294 |
|
| 295 |
def dispatch(self, request, *args, **kwargs): |
| 296 |
if request.get_preferred_type(self.accepted_media_types) is None: |
| 297 |
# No format in common. |
| 298 |
return HttpResponse( |
| 299 |
status_code=406, headers={"Accept": ",".join(self.accepted_media_types)} |
| 300 |
) |
| 301 |
|
| 302 |
return super().dispatch(request, *args, **kwargs) |
| 303 |
|
| 304 |
def form_invalid(self, form): |
| 305 |
response = super().form_invalid(form) |
| 306 |
accepted_type = self.request.get_preferred_type(self.accepted_media_types) |
| 307 |
if accepted_type == "text/html": |
| 308 |
return response |
| 309 |
elif accepted_type == "application/json": |
| 310 |
return JsonResponse(form.errors, status=400) |
| 311 |
|
| 312 |
def form_valid(self, form): |
| 313 |
# We make sure to call the parent's form_valid() method because |
| 314 |
# it might do some processing (in the case of CreateView, it will |
| 315 |
# call form.save() for example). |
| 316 |
response = super().form_valid(form) |
| 317 |
accepted_type = self.request.get_preferred_type(self.accepted_media_types) |
| 318 |
if accepted_type == "text/html": |
| 319 |
return response |
| 320 |
elif accepted_type == "application/json": |
| 321 |
data = { |
| 322 |
"pk": self.object.pk, |
| 323 |
} |
| 324 |
return JsonResponse(data) |
| 325 |
|
| 326 |
.. versionchanged:: 5.2 |
| 327 |
|
| 328 |
The :meth:`.HttpRequest.get_preferred_type` method was added. |