CRUD with Django

Heelloooo friends!
Welcome back to my blog page.

Today you will get the code of CRUD application in Django.

What is CRUD?

C - CREATE
R - RETRIEVE
U - UPDATE
D - DELETE

views.py

from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Person

#RETRIEVE
def home(request):
    #Retrieve all the persons' datas.
    get_persons = Person.objects.all()
    params = {'datas': get_persons}
    return render(request, 'home.html', params)


#CREATE
def add_person(request):
    if request.method == 'POST':
        fname = request.POST['fname']
        lname = request.POST['lname']
        age = request.POST['age']
        is_married = request.POST['bool']

        create_person = Person.objects.create(first_name=fname, last_name=lname, age=age, is_married=is_married)
        create_person.save()
        return redirect('home')
    else:
        return HttpResponse('GET request is not allowed.')


#UPDATE
def update_person(request, id):
    get_person = get_person = Person.objects.get(id=id)
    params = {'data': get_person}
    return render(request, 'update.html', params)


def update(request, id):
    get_person = get_person = Person.objects.get(id=id)
    if request.method == 'POST':
        fname = request.POST['fname']
        lname = request.POST['lname']
        age = request.POST['age']
        is_married = request.POST['bool']

        get_person.first_name = fname
        get_person.last_name = lname
        get_person.age = age
        get_person.is_married = is_married
        get_person.save()
    else:
        return HttpResponse('Error')

    return redirect('home')



#DELETE
def delete_person(request, id):
    get_person = Person.objects.get(id=id)
    get_person.delete()
    return HttpResponse("person deleted")

url.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('create/', views.add_person, name='add_person'),
    path('<str:id>/update_person/', views.update_person, name='update_person'),
    path('<str:id>/update/', views.update, name='update'),
    path('delete/<str:id>/', views.delete_person, name='delete_person'),
]

models.py

from django.db import models

# Create your models here.
class Person(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    age = models.IntegerField()
    is_married = models.CharField(max_length=30)

    def _str_(self):
        return self.first_name

admin.py

from django.contrib import admin
from .models import Person

# Register your models here.

admin.site.register(Person)

home.html

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <title>Hello, world!</title>
  </head>
  <body>
    <div class="container w-50">
        <h2 class="my-5">CRUD with DJANGO</h2>

        <ul class="nav nav-tabs" id="myTab" role="tablist">
            <li class="nav-item" role="presentation">
              <button class="nav-link active" id="home-tab" data-bs-toggle="tab" data-bs-target="#home" type="button" role="tab" aria-controls="home" aria-selected="true">Create</button>
            </li>
            <li class="nav-item" role="presentation">
              <button class="nav-link" id="profile-tab" data-bs-toggle="tab" data-bs-target="#profile" type="button" role="tab" aria-controls="profile" aria-selected="false">Retreive</button>
            </li>

          </ul>
          <div class="tab-content" id="myTabContent">
            <div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">
                <form action="{% url 'add_person' %}" method="post">
                {% csrf_token %}
                <div class="mb-3">
                    <label for="exampleFormControlInput1" class="form-label">First Name</label>
                    <input type="text" class="form-control" name="fname" id="exampleFormControlInput1" placeholder="Madhuban">
                  </div>
                  <div class="mb-3">
                    <label for="exampleFormControlInput2" class="form-label">Last Name</label>
                    <input type="text" class="form-control" name="lname" id="exampleFormControlInput2" placeholder="Khatri">
                  </div>
                  <div class="mb-3">
                    <label for="exampleFormControlInput3" class="form-label">Age</label>
                    <input type="number" class="form-control" name="age" id="exampleFormControlInput3" placeholder="21">
                  </div>
                  <div class="mb-3">
                    <label for="exampleFormControlInput4" class="form-label">Are you Single?</label>
                    <select class="form-control" name="bool" id="exampleFormControlInput4">
                        <option>Yes</option>
                        <option>No</option>
                    </select>
                  </div>
                  <div class="mb-3">
                    <input type="submit" class="form-control btn btn-warning" value="Add">
                  </div>
                </form>
            </div>
            <div class="tab-pane fade" id="profile" role="tabpanel" aria-labelledby="profile-tab">
                <table class="table">
                    <thead>
                      <tr>
                        <th scope="col">#</th>
                        <th scope="col">First Name</th>
                        <th scope="col">Last Name</th>
                        <th scope="col">Is Married</th>
                        <th scope="col">Action</th>
                      </tr>
                    </thead>
                    <tbody>
                        {% for data in datas %}
                            <tr>
                                <th scope="row">{{data.id}}</th>
                                <td>{{data.first_name}}</td>
                                <td>{{data.last_name}}</td>
                                <td>{{data.is_married}}</td>
                                <td>
                                    <a href="{% url 'update_person' data.id %}" class="btn btn-sm btn-primary">Update</a>    
                                    <a href="{% url 'delete_person' data.id %}" class="btn btn-sm btn-danger">Delete</a>
                                </td>
                            </tr>
                        {% endfor %}

                    </tbody>
                  </table>
            </div>

          </div>
    </div>


    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>


  </body>
</html>

update.html

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <title>Hello, world!</title>
  </head>
  <body>
    <div class="container">
        <h2 class="my-5">Update Person</h2>
        <form action="{% url 'update' data.id %}" method="post">
          {% csrf_token %}
          <div class="mb-3">
              <label for="exampleFormControlInput1" class="form-label">First Name</label>
              <input type="text" class="form-control" name="fname" id="exampleFormControlInput1" value="{{data.first_name}}">
            </div>
            <div class="mb-3">
              <label for="exampleFormControlInput2" class="form-label">Last Name</label>
              <input type="text" class="form-control" name="lname" id="exampleFormControlInput2" value="{{data.last_name}}">
            </div>
            <div class="mb-3">
              <label for="exampleFormControlInput3" class="form-label">Age</label>
              <input type="number" class="form-control" name="age" id="exampleFormControlInput3" value="{{data.age}}">
            </div>
            <div class="mb-3">
              <label for="exampleFormControlInput4" class="form-label">Are you Single?</label>
              <select class="form-control" name="bool" id="exampleFormControlInput4">
                  {% if data.is_married == 'Yes' %}
                  <option>Yes</option>
                  <option>No</option>
                  {% else %}
                  <option>No</option>
                  <option>Yes</option>
                  {% endif%}
              </select>
            </div>
            <div class="mb-3">
              <input type="submit" class="form-control btn btn-warning" value="Update">
            </div>
          </form>
    </div>



    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>


  </body>
</html>

17