Django CreateView

CreateView

  • Django comes with a reusable class based views and CreateView is one of them.
  • It's similar to the FormView and on top of the FormView it added a extra functionality to store the form data into the database table.
  • It's a view for displaying a form, and rendering a template response and create the data into database table.

When to use CreateView?

  • When we have requirement of validating and storing the information into the database table
  • It allows us to quickly implement the requirement
  • It takes few lines of code to implement it.

UML diagram for CreateView

django CreateView

  • Above is the UML diagram for CreateView.
  • It inherits the classes BaseCreateView, ModelFormMixin, FormMixin, TemplateResponseMixin, ProcessFormView, ContextMixin, View, etc.
  • we can check the code for CreateView at github.
  • It comes with request methods GET and POST.
  • GET method will render the form with context
  • POST method will post the data to the server and renders the form again if has any errors otherwise it will save data into the database and redirect it to the success_url mentiond in the CreateView.
  • can override get_context_data to send extra context to the template.
  • can override get_form_class for conditional rendering of form
  • can override get_success_url for conditional successful redirect.
  • can override form_valid and form_invalid whenever required.

Usage of CreateView in django

Let's consider a library website where we keep the track of the books. If a new books comes in the the admin needs to add it to the database. so, let's implement this scenario with CreateView

models.py

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length = 200)
    description = models.TextField()

    def __str__(self):
        return self.title

views.py

from django.views.generic.edit import CreateView
from .models import Book

class BookCreateView(CreateView):
    model = Book
    fields = ['title', 'description']
    template_name = "book_create.html"
    success_url = "/thank-you/"

urls.py

from django.urls import path

from .views import BookCreateView
urlpatterns = [
    path('books/create/', BookCreateView.as_view()),
]

book_create.html

<form method="POST" enctype="multipart/form-data">

    <!-- Security token -->
    {% csrf_token %}

    <!-- Using the form -->
    {{ form.as_p }}

    <!-- submit button -->
    <input type="submit" value="Submit">
</form>

Create a django app and use the above blocks of code to implements the CreateView in django. Once you done that you can access localhost:8000/books/create/ and create a book then check the database for an entry. It's that simple folks to use django class based CreateView

References:

  1. https://docs.djangoproject.com/en/3.2/ref/class-based-views/generic-editing/#django.views.generic.edit.CreateView
  2. https://github.com/django/django/blob/main/django/views/generic/edit.py#L175