Django CRUD (Create, Retrieve, Update, Delete) Function Based Views

Django REST Framework is a robust and flexible toolkit for building web applications without dependency variables. Django is based on MVT architecture i.e. Model View Template architecture and performs CRUD operations. CRUD is a short abbreviation for Create, Retrieve, Update and Delete, these are the basic operations that one should know while making any web app. In this blog we will learn about django CRUD operations.

Django CRUD (Create, Retrieve, Update, Delete) Function Based Views
CRUD

Create :- create new entries in your database

Retrieve :- retrieve or fetch all or some data from your database

Update :- update or edit data in your database.

Delete :- delete data from database.

Implementations

Step 1. Create Django Project

We are first going to create a django project, an app inside that project and then going to install newsapi-python, which will play a major role in our project.

1. Create a Django project.

django-admin startproject blog16

2. Create an app in that django-project.

python manage.py startapp CRUD

3. Add your app name in installed apps.

Settings.py

INSTALLED_APPS = [
    'blog16',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

Step 2. Add files and Folder to the Django Project

We need to create a template folder in the django folder and a urls.py file in the app folder.

  1. Create a new folder in the django folder(here, blog16 folder) save it with the name template.
  2. Add the path for this template folder in blog16 > settings.py .

Settings.py

import os
 
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

3. Create a new file in the app folder(here, CRUD) save it with the name urls.py .

4. Add path for this url.py file in blog16> urls.py .

Urls.py

from django.contrib import admin
from django.urls import path,include
urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('CRUD.urls'))
]

Step3. Performing Operations

3.1 Create operation

Here we had to first connect with the database, then after that we needed to create a model and store the input from the user in our database. Let’s understand each step one by one.

  1. Connect with Database and create an html file from where we are going to get input from the user, which we had to store in our database.

Add the following code in your settings.py file according to your database credentials.

Settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'blog16',
        'USER': 'postgres',
        'PASSWORD': '2320',
        'HOST': 'localhost'
    }
}

Create an Index.html file under templates folder from where we will get the data that’s need to be store in the database, one thing to be noted that you have to use form tag for this and yes don’t forget to put method= “post” and {% csrf_token %}, if you create your own html file. You can add the following code for simple html file.

Index.html

<html>
 
<head>
    <title>C.R.U.D</title>
    <style>
        .container {
            margin-left: 550px;
            margin-top: 150px;
            width: 300px;
            height: 100px;
            padding: 15px;
            background-color: aquamarine;
        }
    </style>
</head>
 
<body>
    <p style="margin-left:550px;"><a href="retrieve">Check data</a></p>
    <div class="container">
        <table>
            <tbody>
                <form action="create" method="POST">
                    {% csrf_token %}
                    <tr>
                        <td> Name</td>
                        <td><input type="text" name="name" required></td>
                    </tr>
                    <tr>
                        <td> Age</td>
                        <td><input type="text" name="age" required></td>
                    </tr>
                    <tr>
                        <td> Address</td>
                        <td><textarea name='address' required></textarea></td>
                    </tr>
                    <tr>
                        <td><button>Submit</button></td>
                    </tr>
                </form>
            </tbody>
        </table>
    </div>
</body>
 
</html>

Output :-

Django CRUD (Create, Retrieve, Update, Delete) Function Based Views

Create a table in models.py

Models.py

from django.db import models
 
# Create your models here.
class Details(models.Model):
    name=models.CharField(max_length=100)
    age=models.IntegerField()
    address=models.TextField(max_length=255)

Run migrations

python manage.py makemigrations
python manage.py migrate

Now, provide the path for the index page in urls.py of (here, CRUD) app.

Urls.py

from django.urls import path
from . import views
from django.conf.urls import url
 
urlpatterns = [
    path('',views.index,name='index'),
    path('create',views.create,name="create"), 
]

At last add the function for creating new entries in views.py.

Views.py

from django.shortcuts import render,redirect
from .models import Details
# Create your views here.
def index(request):
    return render(request,'index.html')
 
def create(request):
    if request.method=="POST":
        name=request.POST['name']
        age=request.POST['age']
        address=request.POST['address']
            obj=Details.objects.create(name=name,age=age,address=address)
        obj.save()
        return redirect('/')
3.2 Retrieve operation

In this operation we want to fetch data from the database, here we have two options for fetching, either to get all data or specific data. In this case we will fetch all data only.

Create a html file where you want to show your data, here we are creating a retrieve.html file in our template folder. We had added two anchor tags to perform delete and edit operation but in this file they will not perform any operation because these operations we will see in later steps.

Retrieve.html

<html>
 
<head>
    <title>C.R.U.D</title>
    <style>
        table {
            margin-left: 550px;
            margin-top: 150px;
            column-width: 20px;
            font-size: 20px;
            border: 5px solid black;
            padding: 5px;
        }
 
        thead {
            padding: 10px;
        }
 
        tbody {
            padding: 10px;
        }
    </style>
</head>
 
<body>
    <p style="margin-left:550px;"><a href="/">Home</a></p>
    <div class="container">
        <table border="5px solid #000;">
            <tbody>
 
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Age</th>
                        <th>City</th>
                        <th>Edit</th>
                        <th>Delete</th>
                    </tr>
 
                </thead>
            <tbody>
                {% for i in details %}
                <tr>
                    <td style="padding:10px;">{{i.name}}</td>
                    <td style="padding:10px;">{{i.age}}</td>
                    <td style="padding:10px;">{{i.address}}</td>
                    <td style="padding:10px;"><a href="#">Edit</a></td>
                    <td style="padding:10px;"><a href="#">Delete</a></td>
                </tr>
                {% endfor %}
            </tbody>
            </tbody>
        </table>
    </div>
</body>
 
</html>

Now, provide the path for the retrieve page in urls.py of (here, CRUD) app. After adding the path your urls.py file will look like this.

Urls.py

from django.urls import path
from . import views
from django.conf.urls import url
 
urlpatterns = [
    path('',views.index,name='index'),
    path('create',views.create,name="create"),
    path('retrieve',views.retrieve,name="retrieve"),
]

At last add the function for redirecting in views.py.

Views.py

from django.shortcuts import render,redirect
from .models import Details
 
def retrieve(request):
    details=Details.objects.all()
    return render(request,'retrieve.html',{'details':details})

Output :-

Retrieving data
3.3 Update operation

In this operation we want to update our data present in the database. Here, first we need to create a page where user can see his old data and make changes in it so we will create one function name edit for redirecting user to that page, second we have to create a new file in our app folder which is forms.py to reflect changes in the data and third add a new function name update which will validate the form and make changes.

First add the following action in the anchor tag of the edit option which was there in the Retrieve.html file.

Retrieve.html

<td style="padding:10px;"><a href="{% url 'edit' i.pk %}">Edit</a></td>

Create edit page

Edit.html

<html>
 
<head>
    <title>C.R.U.D</title>
    <style>
        .container {
            margin-left: 550px;
            margin-top: 150px;
            width: 300px;
            height: 100px;
            padding: 15px;
            background-color: aquamarine;
        }
    </style>
</head>
 
<body>
    <h1>Edit</h1>
    <p style="margin-left:550px;"><a href="retrieve">Check data</a></p>
    <div class="container">
        <table>
            <tbody>
                <form action="/update/{{object.id}}" method="POST">
                    {% csrf_token %}
                    <tr>
                        <td> Name</td>
                        <td><input type="text" name="name" value={{object.name}}></td>
                    </tr>
                    <tr>
                        <td> Age</td>
                        <td><input type="text" name="age" value={{object.age}}></td>
                    </tr>
                    <tr>
                        <td> Address</td>
                        <td><textarea name='address'>{{object.address}}</textarea></td>
                    </tr>
                    <tr>
                        <td><button>Submit</button></td>
                    </tr>
                </form>
            </tbody>
        </table>
    </div>
</body>
 
</html>
Django CRUD (Create, Retrieve, Update, Delete) Function Based Views

Forms.py

from django import forms
from .models import Details
 
class detailsform(forms.ModelForm):
    class Meta:
        model=Details
        fields="__all__"

In urls.py we will be adding two urls one for redirecting to the edit page and other for updating the changes.

Urls.py

from django.urls import path
from . import views
from django.conf.urls import url
 
urlpatterns = [
    path('',views.index,name='index'),
    path('create',views.create,name="create"),
    path('retrieve',views.retrieve,name="retrieve"),
    path('edit/<int:id>',views.edit,name="edit"),
    path('update/<int:id>',views.update,name="update"),
]

Views.py

from .forms import detailsform
def edit(request,id):
    
    object=Details.objects.get(id=id)
    return render(request,'edit.html',{'object':object})
    
def update(request,id):
    object=Details.objects.get(id=id)
    form=detailsform(request.POST,instance=object)
    if form.is_valid:
        form.save()
        object=Details.objects.all()
        return redirect('retrieve')

Output :-

Editing
Making changes
After editing
After editing
3.4 Delete operation

In this operation we want to delete our data present in the database. 

First add the following action in the anchor tag of the delete option which was there in the Retrieve.html file.

Retrieve.html

<td style="padding:10px;"><a href="{% url 'delete' i.pk %}">Delete</a></td>

Add the following code in urls.py, after this your urls.py will look something like this.

Urls.py

from django.urls import path
from . import views
from django.conf.urls import url
 
urlpatterns = [
    path('',views.index,name='index'),
    path('create',views.create,name="create"),
    path('retrieve',views.retrieve,name="retrieve"),
    path('edit/<int:id>',views.edit,name="edit"),
    path('update/<int:id>',views.update,name="update"),
    url(r'^delete_product/(?P<pk>[0-9]+)/$', views.delete,name="delete"),  
]

Views.py

def delete(request,pk):   
        Details.objects.filter(id=pk).delete()
        return redirect('retrieve')
before deleting
Before deleting
Django CRUD (Create, Retrieve, Update, Delete) Function Based Views
After deleting

Conclusion

So, we learned about django CRUD operations. I hope this blog will be useful for you and helps you to understand each and every step. Hope all your doubts get cleared. Thank you.