How to create a class-based view in Django
Overview
In this shot, we will learn how to create a class-based view in Django by creating a full
Django is an open-source, high-level Python web framework that encourages clean, pragmatic design and rapid development.
How to install
Step 1
pip install pipenv
pipenv shell
pipenv install django
Step 2
django-admin startproject CRUD./
python manage.py startapp codebase
Step 3
python manage.py migrate
python manage.py runserver
Step 4
Once the settings are initialized, we should make the following changes inside the settings.py file:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'codebase'
]
Note:
settings.pyhelps register the application and packages that are installed. It also writes the rules.
Step 5
We add the following code to the models.py file located inside the app folder:
from django.db import models
from django.urls import reverse
class CRUD(models.Model):
name = models.CharField(max_length=30)
age = models.IntegerField()
level = models.CharField(max_length=30)
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
Note:
models.pyis responsible for creating the model for the database.
Step 6
We write the following code inside the admin.py file:
from django.contrib import admin
from .models import CRUD
admin.site.register(CRUD)
Note: In the
admin.pyfile, we import and register our created model. By doing so, we can view the model when we are logged in as administrator.
Step 7
With the configuration complete, we can create a file for the form. In our case, the file is named forms.py. Add the following code inside forms.py file:
from django import forms
from .models import CRUD
class CRUDFORM(forms.ModelForm):
name = forms.CharField(widget=forms.TextInput(attrs={
"class": "form-control",
"placeholder": "name"
}))
age= forms.CharField(widget=forms.TextInput(attrs={
'type': "number",
"class": "form-control",
"placeholder": "age"
}))
level = forms.CharField(widget=forms.TextInput(attrs={
"class": "form-control",
"placeholder": "level"
}))
class Meta:
model = CRUD
fields = [
'name', 'age','level'
]
Note: The
forms.pyfile is responsible for creating Django forms, which are like HTML forms, but dynamic.
Step 8
We can now create a view for our project with the form we just created. The corresponding views.py file is as follows:
from django.shortcuts import redirect, render, get_object_or_404, reverse
from django.views.generic.edit import UpdateView
from .models import CRUD
from .forms import CRUDFORM
from django.views.generic import ListView, CreateView, DeleteView, DetailView
# home view
class Home(ListView):
model = CRUD
template_name = 'app/base.html'
# create view
class Create(CreateView):
model = CRUD
template_name = 'app/create.html'
form_class = CRUDFORM
# if the form, submits, to go back to the homepage automatically
def get_success_url(self):
return reverse('home')
# detail view
class Detail(DetailView):
model = CRUD
template_name = 'app/detail.html'
# update view
class Update(UpdateView):
model = CRUD
template_name = 'app/create.html'
form_class = CRUDFORM
# if the form, submits, to go back to the homepage automatically
def get_success_url(self):
return reverse('home')
# delete view
class Delete(DeleteView):
model = CRUD
template_name = 'app/delete.html'
# if the form, submits, to go back to the homepage automatically
def get_success_url(self):
return reverse('home')
Note: The
views.pyfile is used to create functions or classes that visualize how a route will operate.
Step 9
- We create a folder and name it
templatesin thecodebase. - We create another folder and name it
appinside thetemplatesfolder. - We create
base.html,create.html,detail.html, anddelete.htmlfiles inside theappfolder.
Add the following code inside base.html:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Crud</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"></head><body><div class="container mt-3"><ul><!-- Iterate over object_list --><a href="{% url 'create' %}">Create </a>{% for object in object_list %}<!-- Display Objects --><li><a href="{% url 'detail' object.id %}">{{ object.name }}</a> - <a class="ml-5" href="{% url 'update' object.id %}">Update</a> - <a class="ml-5" href="{% url 'delete' object.id %}">Delete</a></li><li>{{ object.age }}</li><li>{{ object.level }}</li><hr/><!-- If object_list is empty -->{% empty %}<li>No objects yet.</li>{% endfor %}</ul></div></body></html>
Add the following code inside create.html:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Crud</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"></head><body><div class="container mt-5"><h1 class="text-center">CRUD</h1><form method="POST" action="">{% csrf_token %}{{form.as_p}}<input type="submit" class="btn btn-outline-success" ></form></div></body>
Add the following code inside detail.html:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css"rel="stylesheet"integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"></head><body><div class="container"><ul class="list-group"><a href="{% url 'home'%}">Home</a><li class="list-group-item">{{object.name}}</li><li class="list-group-item">{{object.age}}</li><li class="list-group-item">{{object.level}}</li></ul></div></body></html>
Add the following code inside delete.html:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Crud</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"></head><body><div class="container mt-5"><form method="POST" action="">{% csrf_token %}<a href="{% url 'home'%}">Home</a><button class="btn btn-outline-danger" >Delete</button></form></div></body>```
Step 10
Go to the CRUD folder and make the following amends in the urls.py file:
from django.contrib import admin
from django.urls import path, include
# importing from app folder, the view file
from app.views import Home, Create, Detail,Update, Delete
urlpatterns = [
path('admin/', admin.site.urls),
path('',Home.as_view(), name="home" ),
path('create/', Create.as_view(), name='create'),
path('<pk>/', Detail.as_view(), name='detail'),
path('update/<pk>/', Update.as_view(), name='update'),
path('delete/<pk>/', Delete.as_view(), name='delete'),
]
Note: The
urls.pyfile is used to create a different URL route.
Step 11
Now we’re ready to run the following commands to make migrations to the code:
python manage.py makemigrations
python manage.py migrate
Step 12
To create a super-user, run the following command:
python manage.py createsuperuser
Step 13
To start the server, run:
python manage.py runserver
Note: To access the admin panel, visit
https://127.0.0.1:8000/adminon your local machine. To access the homepage, visithttps://127.0.0.1:8000on your local machine.