How to use CreateView in Django?

Published On: 15/09/2022 | Category: Django

Hi Dev,

This tutorial will provide example of how to use createview in django. This tutorial will give you simple example of how to use class based views in django. I explained simply about how to use createview in django with example. you will learn django createview class based views example.

Django Class based views are simpler and efficient to manage than function-based views. A function based view with tons of lines of code can be converted into a class based views comes with few lines only.

For in this example, CreateView is a class view that helps you to display a model's form with validation errors and save objects.

let's see bellow example here you will learn how to use createview in django.

Step 1: Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example

Step 2: Create a App

Now we'll create a single app called core to store a list of post names. We're keeping things intentionally basic. Stop the local server with Control+c and use the startapp command to create this new app.

python3 startapp core

Step 3: Update

Next, then update INSTALLED_APPS within our file to notify Django about the app.

Next, you need to add it in the file as follows:


Step 4: Creating the Model

In this step we will require the database model for storing article details in article table.Open the file and add the following code:

from django.db import models

class Article(models.Model):
    title= models.CharField(max_length=300)
    content= models.TextField()
    pub_date = models.DateTimeField(auto_now_add= True)

Ok, all set. We can engender a migrations file for this change, then integrate it to our database via migrate.

python makemigrations
python migrate

Step 5: Create a Form

In this step We need to create a form that will be used .like add a bootstrap class and validation etc.. plus we need to add custom styling.

from django import forms
from .models import *

class ArticleForm(forms.ModelForm):
    title = forms.CharField(
                "placeholder": "Title",
        ),error_messages={'required': 'The Title is required.'})
    content = forms.CharField(
                'rows': 5,
                "placeholder": "Content",
        ),error_messages={'required': 'The Content is required.'})

    class Meta:
        model = Article
        fields = ['title','content',]

Step 6: Creating the Views

In this step, we need to configure our views. The ArticleCreateView page will template and define form_class and Article model as well as, open the file and add:

from django.shortcuts import render
from django.views.generic.edit import CreateView
from .forms import *
from .models import *

class ArticleCreateView(CreateView):
    model = Article
    form_class = ArticleForm
    template_name = 'article.html'
    success_url = "/create"

Step 7: Creating the Template

Next, then with your text editor create new templates files: core/templates/article.html file and the add:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <link rel="stylesheet" href="[email protected]/dist/css/bootstrap.min.css">
    <style type="text/css">
            background-color: #f7fcff;
    <div class="container mt-5 pt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h4>how to use CreateView in Django? - <span class="text-primary"></span></h4>
                    <div class="card-body">
                        <form method = "post" enctype="multipart/form-data">
                            {% csrf_token %}
                            {{ form.as_p }}
                            <button type="submit" class="btn btn-success">Submit</button>

Step 8: Creating URLs

In this section, we need a file within the core app however Django doesn't create one for us with the startapp command. Create core/ with your text editor and within this file we'll import yet-to-be-created function for each--ArticleCreateView Note as well that we set an optional URL name for each.

Here's what it looks like:

from django.urls import path
from .views import ArticleCreateView

urlpatterns = [
    path('create/', ArticleCreateView.as_view()),

Next, we require to add a URL path for our example app which can be done by importing include and setting a path for it.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('', include('core.urls')),

Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python runserver

Next, go to the http://localhost:8000/create address with a web browser.

Django Admin Interface:

I Hope It will help you....

Happy Pythonic Coding!