Every Course in $5, Hurry Up!

Build a Django CRUD Application | Django Tutorials

Django CRUD Application copy
Django

Build a Django CRUD Application | Django Tutorials

Build a Django CRUD Application

In this article, you will learn how to build a Django CRUD Application step by step. We have shared each and everything related to building CRUD applications in detail. Sure that, if you read this complete article you will get techniques and easy methods to build Django CRUD application properly. Let’s learn!

What is a CRUD application?

It is very common as an Important application to develop for beginners if you take an interest in the development field. CRUD means Create, Read, Update and Delete. Almost every websites or application have these features but beginners don’t know. They understood that it is a new thing but we used such functionality in every application.

It is the application in which user can create post/article/any media like pictures, video or audio, etc, it user like, can view how it is looking bad or good, or if the user wants to make any updation or editing such application allow to update content, and if the user wants to delete any created content, then application allows a user to delete. Such functionality like a website is called a CRUD application.

Why do need to create CRUD applications for beginners?

As we have mentioned that almost every application has a CRUD functionality, if beginners develop a CRUD application, then it will be good for beginners to work with any kind of application. If you learn any web frameworks, CMS, system, MVT, MVC, you will be given an assignment to build a CRUD application in that technology. If you cannot develop a CRUD application, it means, you did not learn anything.

Learn MVC vs MVT

But in this article we will learn how to build a Django CRUD application, that is very easy to develop. So in the following section, we will share the complete source code with an explanation step by step, which makes it easy for beginners to understand.

Steps to create Django CRUD Application

To create a Django application that performs CRUD operations, follow the following steps.

1. Start a Django Project

The very first step is to start a project in which you will create multiple applications.  To start a Django project run the following command in the visual studio command prompt or other Ediot you are using.

django-admin startproject school

2. Start an App

After creating a project you have to create an application in which you will add templates, static folders, other functionalities like creating Django forms, models. etc. So run the following command to create an application in your Django project.

python manage.py startapp student

3. Include App in Installed App

This step is very important, sometimes beginners forget this step. When you install any application, libraries, packages you have to include them in the Installed apps list to inform Django. So you also need to add your application to the INSTALLED_APPS  list.

You have to open the settings.py file of your project folder and add your application name with quotes as mentioned at the last.

# Application definition for Django CRUD Application
INSTALLED_APPS = [
    ‘django.contrib.admin’,
    ‘django.contrib.auth’,
    ‘django.contrib.contenttypes’,
    ‘django.contrib.sessions’,
    ‘django.contrib.messages’,
    ‘django.contrib.staticfiles’,
    ‘student’,
]

4. Project Structure

When you run a command for creating a project you will get a number of by default files as asgi.py, wsgi.py, urls.py, settings.py,__init__.py. You also get default files when you start an app as models.py views.py, tests.py, admin.py, apps.py __init__.py. In the following, you will look at the screenshot that is showing our complete project structure.

Build a Django CRUD Application

5. Create a Model

Model is used to define a project organization’s entity. The entity is the real world thing like the place, person, things, concepts or events, etc. So car, student, table, mobile, fan, etc are examples of an entity. When we create a model class, it converts to a database table in the database using commands.

// In your project application folder, models.py file

from django.db import models
class Student(models.Model):
    s_name = models.CharField(max_length=100)
    s_email = models.EmailField()
    s_subject = models.CharField(max_length=100)
    s_contact = models.CharField(max_length=100)

6. Make Migrations and Migrate

After creating a Django model class you need to run a command which generates a SQL query in order to make a table according to your model class descriptions. So to migration, use the following command:

python manage.py makemigrations

After doing this you need to run another command, which process of applyment on migrations file. After runnign following command a tabel wil be created in the databse.

python manage.py migrate

7. Create a ModelForm

// in your project application folder forms.py file

from django import forms
from student.models import Student
class StudentForm(forms.ModelForm):
    class Meta:
        model = Student
        fields = “__all__”

8. Create View Functions

// in your project application folder, views.py

from django.shortcuts import render, redirect
from student.forms import StudentForm
from student.models import Student
# Create views
def std(request):
    if request.method == “POST”:
        form = StudentForm(request.POST)
        if form.is_valid():
            form.save()
    else:
        form = StudentForm()
    return render(request,’student/index.html’,{‘form’:form})
def std_show(request):
    student = Student.objects.all()
    return render(request,”student/std_show.html”,{‘student’:student})
def std_edit(request, id):
    student = Student.objects.get(id=id)
    return render(request,’student/std_edit.html’, {‘std’:student})
def std_update(request, id):
    student = Student.objects.get(id=id)
    form = StudentForm(request.POST, instance = student)
    if form.is_valid():
        form.save()
        return redirect(“/std_show”)
    return render(request, ‘student/std_edit.html’, {‘student’: student})
def std_del(request, id):
    student = Student.objects.get(id=id)
    student.delete()
    return redirect(“/std_show”)

9. URL Patterns

//in Django Project urls.py

from django.contrib import admin
from student import views
from django.urls import path
urlpatterns = [
    path(‘admin/’, admin.site.urls),
    path(‘std’, views.std),
    path(‘std_show’,views.std_show),
    path(‘std_edit/<int:id>’, views.std_edit , name=”std_edit”),
    path(‘std_update/<int:id>’, views.std_update , name=”std_update”),
    path(‘std_delete/<int:id>’, views.std_del, name=”std_del”),
]

10. Organize Templates

The template is the collection of HTML, CSS JS, and other frontend skills, in which your content is displayed to the user. You have to create a template folder inside the application folder with the name of the application name as ‘student’. Then create the required files as I have mentioned.

If you want to learn more about the Django template, then we have published a complete Django tutorial on it. Click on the linked page.

You need to create following tempalte to get proper work with us.

  • Index.html
  • std_edit.html
  • std_show.html

# create a html file with name ‘index’ and paste below code

<!doctype html>
<html lang=”en”>
<head>
    <!– Required meta tags –>
    <meta charset=”utf-8″>
    <meta name=”viewport” content=”width=device-width, initial-scale=1, shrink-to-fit=no”>
    <!– Bootstrap CSS –>
    <link rel=”stylesheet” href=”https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css”
        integrity=”sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh” crossorigin=”anonymous”>
    <title>Student CRUD Application</title>
</head>
<body>
    <h1>Student CRUD Application</h1>
    <form method=”POST” class=”post-form” action=” /std”>
                {% csrf_token %}
        {{form}}
        <input type=”submit” class=”btn btn-primary” value=”Submit”>
    </form>
    <!– Optional JavaScript –>
    <!– jQuery first, then Popper.js, then Bootstrap JS –>
    <script src=”https://code.jquery.com/jquery-3.4.1.slim.min.js”
        integrity=”sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n”
        crossorigin=”anonymous”></script>
    <script src=”https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js”
        integrity=”sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo”
        crossorigin=”anonymous”></script>
    <script src=”https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js”
        integrity=”sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6″
        crossorigin=”anonymous”></script>
</body>
</html>

# create a html file with name ‘std_show’ and paste below code

<!doctype html>
<html lang=”en”>
<head>
    <!– Required meta tags –>
    <meta charset=”utf-8″>
    <meta name=”viewport” content=”width=device-width, initial-scale=1, shrink-to-fit=no”>
    <!– Bootstrap CSS –>
    <link rel=”stylesheet” href=”https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css”
        integrity=”sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh” crossorigin=”anonymous”>
    <title>Student Django CRUD Application</title>
</head>
<body>
    <table class=”table table-hover”>
        <thead>
            <tr>
                <th></th>
            </tr>
        </thead>
        <tbody>
                <tr>
                        <th>Student ID</th>
                        <th>Student Name</th>
                        <th>Student Email</th>
                        <th>Student Subject</th>
                        <th>Student Contact</th>
                        <th>Actions</th>
                    </tr>
            {% for std in student %}
                <tr>
                        <td>{{std.id }}</td>
                        <td>{{std.s_name }}</td>
                        <td>{{std.s_email }}</td>
                        <td>{{std.s_subject }}</td>
                        <td>{{std.s_contact }}</td>
                        <td>
                                <a  href=”{% url ‘std_edit’ std.id %}”>Edit</a>
                                <a href=”{% url ‘std_del’ std.id %}”>Delete</a>
                            </td>
                    </tr>
            {% endfor %}
        </tbody>
    </table>
    <!– Optional JavaScript –>
    <!– jQuery first, then Popper.js, then Bootstrap JS –>
    <script src=”https://code.jquery.com/jquery-3.4.1.slim.min.js”
        integrity=”sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n”
        crossorigin=”anonymous”></script>
    <script src=”https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js”
        integrity=”sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo”
        crossorigin=”anonymous”></script>
    <script src=”https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js”
        integrity=”sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6″
        crossorigin=”anonymous”></script>
</body>
</html>

# create a html file with name ‘std_edit’ and paste below code

<!doctype html>
<html lang=”en”>
<head>
    <!– Required meta tags –>
    <meta charset=”utf-8″>
    <meta name=”viewport” content=”width=device-width, initial-scale=1, shrink-to-fit=no”>
    <!– Bootstrap CSS –>
    <link rel=”stylesheet” href=”https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css”
        integrity=”sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh” crossorigin=”anonymous”>
    <title>Student Django CRUD Application</title>
</head>
<body>
    <form method=”POST” class=”post-form” action=” /std_update/{{student.id}}”>
                {% csrf_token %}
            <div class=”container”>
            <br>
                <div class=”form-group row”>
                    <label class=”col-sm-1 col-form-label”></label>
                    <div class=”col-sm-4″>
                        <h3>Update Details</h3>
                        </div>
                  </div>
                <div class=”form-group row”>
                    <label class=”col-sm-2 col-form-label”>Student Id:</label>
                    <div class=”col-sm-4″>
                            <input type=”text” name=”id” id=”id_eid” required maxlength=”20″ value=”{{std.id }}” />
                        </div>
                  </div>
              <div class=”form-group row”>
                    <label class=”col-sm-2 col-form-label”>Student Name:</label>
                    <div class=”col-sm-4″>
                            <input type=”text” name=”s_name” id=”id_ename” required maxlength=”100″ value=”{{ std.s_name }}”  />
                        </div>
                  </div>
                <div class=”form-group row”>
                    <label class=”col-sm-2 col-form-label”>Student Email:</label>
                    <div class=”col-sm-4″>
                            <input type=”email” name=”s_email” id=”id_eemail” required maxlength=”254″ value=”{{std.s_email}}”  />
                        </div>
                  </div>
                <div class=”form-group row”>
                    <label class=”col-sm-2 col-form-label”>Student Subject:</label>
                    <div class=”col-sm-4″>
                            <input type=”text” name=”s_subject” id=”id_s_subject” required maxlength=”254″ value=”{{ std.s_subject}}”  />
                        </div>
                  </div>
                <div class=”form-group row”>
                    <label class=”col-sm-2 col-form-label”>Student Contact:</label>
                    <div class=”col-sm-4″>
                            <input type=”text” name=”econtact” id=”id_econtact” required maxlength=”15″ value=”{{ std.s_contact }}”  />
                        </div>
                  </div>
                <div class=”form-group row”>
                    <label class=”col-sm-1 col-form-label”></label>
                    <div class=”col-sm-4″>
                        </div>
                  </div>
        </div>
        <div class=”col-xs-4 col-sm-4 col-md-4 col-lg-4″>
                <button type=”submit” class=”btn btn-success”>Update</button>
        </div>
    </form>
    <!– Optional JavaScript –>
    <!– jQuery first, then Popper.js, then Bootstrap JS –>
    <script src=”https://code.jquery.com/jquery-3.4.1.slim.min.js”
        integrity=”sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n”
        crossorigin=”anonymous”></script>
    <script src=”https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js”
        integrity=”sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo”
        crossorigin=”anonymous”></script>
    <script src=”https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js”
        integrity=”sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6″
        crossorigin=”anonymous”></script>
</body>
</html>

11. Static Files Settings

We are ending to building Django CRUD Application, but one step if have to do. Without this step, CRUD operation will be a complete app but you may need static file management. Static files are the important file for a website or web applications as CSS, JS, JQ, or other related fiels. You have to properly manage these files. We have published a complete article on Django static files management, you can read that article to get more information.

12. Runserver

So, you have done everything, now you have to run your server with this project. If you want to know about how to run a server for your Django project in detail. We have published a complete article on it.

So using the following command you can run a server at port 8000

python manage.py runserver  

After running the server, you will be given a URL, visiting that you can view your Django website:

localhost:8000

Now! what you have to do?

As you have read this article about “build a Django CRUD application”, now you must follow instructions as discussed in this article. In case of any issues or problems, don’t worry, you can discuss them with us.

On other hand, If you have any suggestions or knowledge about this article, you can share it with us, we will appreciate you!

If this article is good then share it on FacebookTwitterPinterestInstagram, etc.

Advanced Tutorials for Beginners

Can Web Design using Python Programming?

FULL Guide | Django messages Framework

Complete Django Template Language Tutorial (DTL)

What Programming Language is used for Data Analytics

Python for Backend Web Development | Complete Guide

Leave your thought here

Your email address will not be published. Required fields are marked *

Select the fields to be shown. Others will be hidden. Drag and drop to rearrange the order.
  • Image
  • SKU
  • Rating
  • Price
  • Stock
  • Availability
  • Add to cart
  • Description
  • Content
  • Weight
  • Dimensions
  • Additional information
  • Attributes
  • Custom attributes
  • Custom fields
Click outside to hide the comparison bar
Compare