Python Django Crud Web Application

Introduction

Django is a free, open-source framework for web applications written in Python. Django offers a large assortment of modules you can use in your projects. Firstly, there are frameworks to save developers a lot of time and headaches wasted, and Django is no different.

python django crud

In this post, we briefly cover the steps needed to create a CRUD app in Django; the steps we will need are:
• Install Django and start a new project
• Make an App
• Create the Model
• Make the Admin Interface (optional)
• Create the View
• Define the URLs (i.e., URL to View mapping)
• Create the Templates

Install Django and Start New Project

django-admin startproject my_proj
cd my_proj

Create a New App

From the Django project directory, we will create a new app called “books” to store our books collection:

py manage.py startapp books

We will also need to register the new app in our Django project, add the app “books” to the INSTALLED_APPS in your my_proj/settings.py:

INSTALLED_APPS = (
 :
 'student',
 :
 )

Create the Model

The model file would be student/models.py:

from django.db import models

class Student(models.Model):
    rollno = models.AutoField(primary_key=True)
    fullname = models.CharField(max_length=30)
    address = models.CharField(max_length=30)
    email = models.CharField(max_length=30)
    age = models.IntegerField()
    des = models.CharField(max_length=30)

After defining the model, you need to provide it to the database:

py manage.py makemigrations 
py manage.py migrate

Admin Interface (Optional)

from django.contrib import admin
from .models import student

admin.site.register(student)

The Views

We will use Django Class-based views to create our app pages, hence, the file student/views.py would look like:

from django.shortcuts import render,redirect
from .models import Student
def SaveStudent(request):
    if request.method=='GET':
        return render(request,'index.html')
    else:
        fullname = request.POST['fulname']
        address = request.POST['add']
        email = request.POST['email']
        age = request.POST['age']
        designation = request.POST['des']
        print(fullname, address, email, age, designation)

#Method 1, it is commented
        # st = Student()
        # st.fullname = request.POST['fulname']
        # st.address = request.POST['add']
        # st.age = request.POST['age']
        # st.email = request.POST['email']
        # st.des = request.POST['des']
        # st.save()
#Method 2
        stu = Student(fullname=fullname,address=address,email=email,age=age,des=designation)
        stu.save()
        return redirect('/students/list/')

def showstudentslist(request):
    all_students = Student.objects.all()
    context = {
        'students':all_students
    }
    return render(request, 'stulist.html', context)

def deletestudents(request,id):
    print(id)
    student = Student.objects.get(rollno=id)
    student.delete()
    return  redirect('/students/list/')

def updatestudents(request,id):
    student = Student.objects.get(rollno=id)
    context = {
        'roll':student.rollno,
        'fn': student.fullname,
        'add': student.address,
        'em': student.email,
        'age': student.age,
        'des': student.des
    }
    return render(request, 'update.html', context)

def updateprocess(request):
    rollno = request.POST['roll']
    fullname = request.POST['fulname']
    address = request.POST['add']
    email = request.POST['email']
    age = request.POST['age']
    designation = request.POST['des']
    print(fullname, address, email, age, designation)

    st = Student()
    st.rollno = request.POST['roll']
    st.fullname = request.POST['fulname']
    st.address = request.POST['add']
    st.age = request.POST['age']
    st.email = request.POST['email']
    st.des = request.POST['des']
    st.save()
    return redirect('/students/list/')

Define the URLs

We need to define app URLs in the file student/urls.py (create the file):

from django.urls import path
from student import views

urlpatterns = [
    path('save/', views.SaveStudent),
    path('list/', views.showstudentslist),
    path('update/<int:id>', views.updatestudents),
    path('update/', views.updateprocess),
    path('delete/<int:id>', views.deletestudents),
]

Templates

For saving student details

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title>Title</title>
   </head>
   <body>
      <h1>Student Registration Form</h1>
      <form action="/students/save/" method="post">
         {% csrf_token %}
         Full Name : <input name="fulname"><br>
         Address : <input name="add"><br>
         email : <input name="email"><br>
         Age : <input name="age"><br>
         Designation : <input name="des"><br>
         <input type="submit" value="Save">
      </form>
   </body>
</html>

For Listing all student details

{% load static %}
<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title>Title</title>
      <link rel="stylesheet" href="{% static 'style.css'%}" type="text/css">
   </head>
   <body>
      <h1 class="stu">Student List</h1>
      <table border="1">
         <tr>
            <th>Rollno</th>
            <th>Fullname</th>
            <th>Address</th>
            <th>Email</th>
            <th>Age</th>
            <th>Action</th>
         </tr>
         {% for a in students %}
         <tr>
            <td>{{a.rollno}}</td>
            <td>{{a.fullname}}</td>
            <td>{{a.address}}</td>
            <td>{{a.email}}</td>
            <td>{{a.age}}</td>
            <td><a href="/students/update/{{a.rollno}}">Update</a> |
               <a href="/students/delete/{{a.rollno}}">Delete</a>
            </td>
         </tr>
         {% endfor %}
      </table>
      {{msg}}
      <a href="/accounts/logout/">logout</a>
   </body>
</html>

For Updating student details

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title>Title</title>
   </head>
   <body>
      <h1>Student Registration Form</h1>
      <form action="/students/update/" method="post">
         {% csrf_token %}
         <input type="hidden" name="roll" value="{{roll}}"><br>
         Full Name : <input name="fulname" value="{{fn}}"><br>
         Address : <input name="add" value="{{add}}"><br>
         email : <input name="email" value="{{em}}"><br>
         Age : <input name="age" value="{{age}}"><br>
         Designation : <input name="des" value="{{des}}"><br>
         <input type="submit" value="Save">
      </form>
   </body>
</html>

We hope you enjoyed the blog. We will be happy to hear your feedback. please visit www.vytcdc.com
Spread the love