Django CRUD Operation using Function-Based Views

Django CRUD Operation using Function-Based Views

Hello Techies,

Django has two types of views. Class-Based Views, and Function-Based Views. So in this blog, I’m going to discuss Django CRUD Operation using Function-Based Views with example. CRUD operations are common tasks in many web applications. So let’s take a  step-by-step look at how to perform this Django CRUD (Create, Read, Update, and Delete) Example or Django CRUD operation using Function-based views.

Refer the below Articles to check how to create Django Projects & CRUD operation using Class Based View:

1) How to create Django project
2) Django CRUD Operation using Class-Based Views
Django CRUD Operation using Function-Based Views. The sample project view you are working on in this tutorial.

1. Introduction

Django is a Python-based web framework that follows the MVT (Model View Template) pattern and allows you to quickly create web applications.

What is Function-Based Views?

A view function, or in short view, is a Python function that takes a web request and responds to the web. This response could be HTML content on a web page or a redirect or a 404 error or anything.


2. Requirements

  • Python installed in the machine: Django is based on Python so you need to have Python installed in your machine.
  • Virtual Environment: Install virtual environment after Python installation. Virtual environment installation will vary according to your OS.
  • Django Installation:  Once the above requirements are met, install Django, and start to implement the Django CRUD operation using the Function-Based Views project.

For Python, Virtual Environment & Django installation check our previous blogs. Below are the links:

For Windows: https://techpluslifestyle.com/technology/how-to-install-django-3-on-windows

For Ubuntu: https://techpluslifestyle.com/technology/how-to-install-django-3-on-ubuntu

Let’s create an application that is based on the Book Library. So in this application, we are using Django CRUD operation using function-based views (add, delete, create, and list book views). I’m using the SQLite database. If you want to use another database, you can configure it in the settings.py file, and then you can use the new database.


3. Django CRUD Operation using Function-Based Views

Let’s start with the Django function-based views tutorial.

Base.html

To avoid duplication in the other templates use the below base.html code.

# templates/base.html

<!DOCTYPE html>
<html lang="en">

<head>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">

  <title>TechPlusLifestyle - Django Crud Operation Function Based-View</title>

  <!-- Bootstrap core CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
</head>

<body>

  <!-- Navigation -->
  <nav class="navbar navbar-expand-lg navbar-dark bg-dark static-top">
    <div class="container">
      <a class="navbar-brand" href="#">LOGO</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarResponsive">
        <ul class="navbar-nav ml-auto">
          <li class="nav-item">
            <a class="nav-link" href="{% url 'home' %}">Home
              <span class="sr-only">(current)</span>
            </a>
          </li>
        </ul>
      </div>
    </div>
  </nav>

  <!-- Page Content -->
  <div class="container">
    <div class="row">
      <div class="col-lg-12">
        {% block content %}
        {% endblock %}
      </div>
    </div>
  </div>

  <!-- Bootstrap core JavaScript -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.slim.min.js"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js" integrity="sha384-LtrjvnR4Twt/qOuYxE721u19sVFLVSA4hf/rRt6PrZTmiPltdZcI7q7PXQBYTKyf" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script></body>
  <script src="https://getbootstrap.com/docs/4.0/assets/js/vendor/holder.min.js"></script>
</html>

Change the below code in settings.py file.

# settings.py

[os.path.join(BASE_DIR, 'templates')]

Create a separate app in this project and add model.py, view.py, url.py, and form.py files to this app. In short, we will put all the source code related to the book library in this app. Once this app is created, add it to the INSTALLED_APPS list in the settings.py file as well as include in the urls.py file.

# settings.py

INSTALLED_APPS = [
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
   'app'
]
# django_crud_function_based_view/urls.py

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

urlpatterns = [
      path('admin/', admin.site.urls),
      path('', include("app.urls")),
]

Let’s create a model in the app to store multiple fields related to the book library, such as name, about, category, author name, and publish date.

Below is the code for the Book model.

# app/models.py

from django.db import models
from django.utils import timezone

class BookLibrary(models.Model):
    class Meta:
        db_table = 'book_library'

    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=150)
    about = models.TextField()
    category = models.CharField(max_length=10)
    author = models.CharField(max_length=500)
    published_at = models.DateTimeField(default=timezone.now)

3.1 List View Function

To create the book list view we will create the List View function.

Add the below code in the app/urls.py file.

# app/urls.py

from django.urls import path
from .views import *

urlpatterns = [
    path('', index, name="home"),
]

The below code is to list the all books which we had created.

# app/views.py

from django.shortcuts import render
from .models import BookLibrary

def index(request):
    context = BookLibrary.objects.all()
    return render(request, 'app/list_books.html', {'context': context})

Now we will add the template for book list view. Below is the HTML code for list view.

# templates/app/list_books.html

{% extends 'base.html' %}

{% block content %}
<br/>
<br/>
<h1>Book List</h1>
<div>
    <a class="btn btn-secondary" href="{% url 'add_book' %}" role="button" style="float:right">Add</a>
</div>
<table class="table" style="margin-top: 5%;">
  <thead class="thead-dark">
    <tr>
      <th scope="col">#</th>
      <th scope="col">Book Name</th>
      <th scope="col">Category</th>
      <th scope="col">Author</th>
      <th scope="col">Action</th>
    </tr>
  </thead>
  <tbody>
    {% if context %}
        {% for each in context %}
            <tr>
              <th scope="row">1</th>
              <td>{{ each.name }}</td>
              <td>{{ each.category | capfirst  }}</td>
              <td>{{ each.author | capfirst  }}</td>
              <td>
                <a href="{% url 'edit_book' each.id %}" class="btn btn-primary">Edit</a>
                <a href="{% url 'delete_book' each.id %}" class="btn btn-danger">Delete</a>
              </td>
            </tr>
        {% endfor %}
    {% else %}
        <tr>
            <th>No Data Found</th>
        </tr>
    {% endif %}
  </tbody>
</table>

{% endblock %}

Rendered HTML

Django CRUD Operation using Function-Based Views (List View Function)

With this our function-based list view was completed now will check the create view.


3.2 Create View Function

Now we will use the Create View Function to create a book.

Below code to add URL for creating books.

# app/urls.py

from django.urls import path
from .views import *

urlpatterns = [
   path('add/', add_book, name="add_book"),
]

Add below code in app/views.py

# app/views.py

from django.shortcuts import render, redirect
from .forms import BookLibForm

def add_book(request):
    template = 'app/add_books.html'
    form = BookLibForm(request.POST or None)
    if form.is_valid():
        form.save()
        return redirect('/')
    context = {"form": form}
    return render(request, template, context)

Now we need form validation as well as we need to give some CSS classes in the template field to decorate the template for which we need the form.py file. Below is the code we are going to use in the form.py file.

# app/forms.py

from django import forms
from .models import BookLibrary


class BookLibForm(forms.ModelForm):
    options = (
        ('sport', 'Sport'),
        ('history', 'History'),
        ('adventure', 'Adventure'),
        ('mystery', 'Mystery'),
        ('horror', 'Horror')
    )
    name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}))
    about = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control'}))
    category = forms.CharField(widget=forms.Select(choices=options, attrs={'class': 'form-control'}))
    author = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}))

    class Meta:
        model = BookLibrary
        fields = ['name', 'about', 'category', 'author']

Template for the Book create view. Add the below code to templates/app/add_books.html.

# templates/app/add_books.html

{% extends 'base.html' %}
{% block title %}
Create Book
{% endblock %}
{% block content %}
<h1>Create Book</h1>
<form class="" method="post" novalidate>
  {% csrf_token %}
  {% for field in form.visible_fields %}
    <div class="form-group">
        <label for="{{ field.id_for_label }}">{{field.label}}</label>
        {{field}}
        {% for error in field.errors %}
            <span class="help-block" style="color:red">{{error}}</span>
        {% endfor %}
    </div>
  {% endfor %}
    <div>
        <input type="submit" name="" value="Submit" class="btn btn-success ">
        <a href="{% url 'home' %}" class="btn btn-default">Cancel</a>
    </div>
</form>
{% endblock %}

Rendered HTML

Django CRUD Operation using Function-Based Views (Create View Function)

Rendered HTML With Validation

Django CRUD Operation using Function-Based Views (Create View Validation)

With this, we are done with our create view function.


3.3 Update View Function

Now we will create an update view function for the book.

Below code for URL.

# app/urls.py

from django.urls import path
from .views import *

urlpatterns = [
    path('edit/<int:pk>', edit_book, name="edit_book"),
]

Add the below code in views.py file.

# app/views.py

from django.shortcuts import render, redirect, get_object_or_404

from .models import BookLibrary
from .forms import BookLibForm


def edit_book(request, pk):
    template = 'app/edit_books.html'
    book = get_object_or_404(BookLibrary, pk=pk)
    form = BookLibForm(request.POST or None, instance=book)
    if form.is_valid():
        form.save()
        return redirect('/')
    context = {"form": form}
    return render(request, template, context)

Template for the Update post.

# templates/app/edit_books.html

{% extends 'base.html' %}
{% block content %}

<div class="container pt-5">
    <h1> Update Book </h1>
    <br/>
    <form method="post" novalidate>
        {% csrf_token %}
        {% for field in form.visible_fields %}
            <div class="form-group">
                <label for="{{ field.id_for_label }}">{{field.label}}</label>
                {{field}}
                {% for error in field.errors %}
                    <span class="help-block" style="color:red">{{error}}</span>
                {% endfor %}
            </div>
        {% endfor %}
        <div>
            <button type="submit" class="btn btn-success">Submit</button>
            <a href="{% url 'home' %}" class="btn btn-default">Cancel</a>
        </div>
    </form>
</div>
{% endblock %}

Rendered HTML

Django CRUD Operation using Function-Based Views (Update View Function)

Rendered HTML With Validation

Django CRUD Operation using Function-Based Views (Update View Function Validation)

This completes your update view function. Let’s move on to the last Django function-based view which is Delete View Function.


3.4 Delete View Function

Now we will create the Delete View Function.

Add the following code in urls.py file.

# app/urls.py

from django.urls import path
from .views import *

urlpatterns = [
    path('delete/<int:pk>', delete_book, name="delete_book"),
]

Add the below code in views.py file.

# app/views.py

from django.shortcuts import render, redirect, get_object_or_404
from .models import BookLibrary


def delete_book(request, pk):
    template = 'app/delete_books.html'
    obj = get_object_or_404(BookLibrary, pk=pk)

    if request.method == 'POST':
        obj.delete()
        return redirect('/')
    context = {"book": obj}
    return render(request, template, context)

Template code for the Delete view function.

# templates/app/delete_books.py

{% extends 'base.html' %}
{% block content %}

<div class="container pt-5">
    <h1> Delete Post </h1>
    <br/>
    <form method="post" novalidate>
        {% csrf_token %}
        <p>Are you sure you want to delete book "{{ book.name }}"?</p>
        <input type="submit" value="confirm">
    </form>
</div>

{% endblock %}

Rendered HTML

Django CRUD Operation using Function-Based Views (Delete View Function)

Here we are done with all the steps of Django CRUD Operation using Function-Based Views.


FAQ on Django CRUD Operation using Function-Based Views

  1. What is function based views in Django?

    Function based views are views from Django defined by the function. These Python functions take web requests and returns a web response.

  2. What are Django models?

    The Django model is a Django built-in feature used to create tables, their fields, and various constraints.

  3. What is CRUD operations Django?

    Django is a Python-based web framework that follows the MVT (Model View Template) pattern and allows you to quickly create web applications. It offers built-in class-based generic views for CRUD operations. CRUD in general means Creating, Retrieving, Updating and Deleting operations on a table in a database.


I hope you understand all the steps which I have covered in this blog which is based on Django CRUD Operation using Function-Based Views. If still you have any query do comment below.

Refer the GIT source code for Django CRUD Operation using the Function-Based Views project.

Leave a Comment