article

Friday, May 1, 2020

Python Django CRUD With Jquery Ajax


Python Django CRUD With Jquery Ajax
 
#views.py
from django.shortcuts import render, redirect
from myapp.models import Member

# Create your views here.
def index(request):
    return render(request, 'index.html')


def create(request):
    member = Member(firstname=request.POST['firstname'], lastname=request.POST['lastname'])
    member.save()
    return redirect('/')

def read(request):
    members = Member.objects.all()
    context = {'members': members}
    return render(request, 'result.html', context)

def edit(request, id):
    members = Member.objects.get(id=id)
    context = {'member': members}
    return render(request, 'edit.html', context)


def update(request, id):
    member = Member.objects.get(id=id)
    member.firstname = request.POST['firstname']
    member.lastname = request.POST['lastname']
    member.save()
    return redirect('/')


def delete(request, id):
    member = Member.objects.get(id=id)
    member.delete()
    return redirect('/')
 
#models.py
from django.db import models

# Create your models here.
class Member(models.Model):
    firstname = models.CharField(max_length=40)
    lastname = models.CharField(max_length=40)
 
    created = models.DateTimeField(auto_now_add=True)
 
    def __str__(self):
        return self.firstname + " " + self.lastname

    class Meta:
        ordering = ['created']
  
    class Meta:  
        db_table = "blog_member"
 
#urls.py
from django.contrib import admin  
from django.urls import path  
from myapp import views  
from django.conf.urls import url

urlpatterns = [  
    path('admin/', admin.site.urls),  
    path('',views.index),
    url(r'^create$', views.create, name='create'),
    url(r'^read$', views.read, name='read'),
    url(r'^edit/(?P\d+)$', views.edit, name='edit'),
    url(r'^edit/update/(?P\d+)$', views.update, name='update'),
    url(r'^delete/(?P\d+)$', views.delete, name='delete'),
] 
//templates/index.html
{% extends 'base.html' %}
{% block body %}
<form class="form-inline">
    {% csrf_token %}
    <div class="form-group">
        <label>Firstname</label>
        <input type="text" id="firstname" class="form-control" style="width:30%;" required="required"/>
        <label>Lastname</label>
        <input type="text" id="lastname" class="form-control" style="width:30%;" required="required"/>
        <button type="button" id="create" class="btn btn-sm btn-primary">Create</button>
    </div>
</form>
<br />
<div id="result"></div>
{% endblock %}
//templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
    {% load static %}
    <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.css' %}"/>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
</head>
<body>
    <nav class="navbar navbar-default">
        <div class="container-fluid">
            <a class="navbar-brand">Cairocoders</a>
        </div>
    </nav>
    <div class="col-md-3"></div>
    <div class="col-md-6 well">
        <h3 class="text-primary">Python Django CRUD With Jquery Ajax</h3>
        <hr style="border-top:1px dotted #ccc;"/>
        {% block body %}

        {% endblock %}
    </div>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script src="{% static 'js/script.js' %}"></script>
</body>
</html>
//templates/edit.html
{% extends 'base.html' %}
{% block body %}
    <form>
        {% csrf_token %}
        <input type="hidden" id="member_id" value="{{ member.id }}"/>
        <div class="form-group">
            <label>Firstname</label>
            <input type="text" id="firstname" value="{{ member.firstname }}" required="required"/>
        </div>
        <div class="form-group">
            <label>Lastname</label>
            <input type="text" id="lastname" value="{{ member.lastname }}" required="required"/>
        </div>
        <div class="form-group">
            <button type="button" id="update" class="btn btn-sm btn-warning">Update</button>
        </div>
    </form>
{% endblock %}
//templates/result.html
<table class="table table-bordered">
    <thead class="alert-success">
        <tr>
            <th>Firstname</th>
            <th>Lastname</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        {% for member in members %}
        <tr>
            <td>{{ member.firstname }}</td>
            <td>{{ member.lastname }}</td>
            <td><center><a class="btn btn-sm btn-warning edit" name="{{ member.id }}">Edit</a> <a class="btn btn-sm btn-danger delete" name="{{ member.id }}">Delete</a></center></td>
        </tr>
        {% endfor %}
    </tbody>
</table>
//static/js/script.js
$(document).ready(function(){
    if($('#result') != null){
        Read();
    }
    $('#create').on('click', function(){
        $firstname = $('#firstname').val();
        $lastname = $('#lastname').val();

        if($firstname == "" || $lastname == ""){
            alert("Please complete the required field");
        }else{
            $.ajax({
                url: 'create',
                type: 'POST',
                data: {
                    firstname: $firstname,
                    lastname: $lastname,
                    csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
                },
                success: function(){
                    Read();
                    $('#firstname').val('');
                    $('#lastname').val('');
                }
            });
        }
    });

    $(document).on('click', '.edit', function(){
        $id = $(this).attr('name');
        window.location = "edit/" + $id;
    });

    $('#update').on('click', function(){
        $firstname = $('#firstname').val();
        $lastname = $('#lastname').val();

        if($firstname == "" || $lastname == ""){
            alert("Please complete the required field");
        }else{
            $id = $('#member_id').val();
            $.ajax({
                url: 'update/' + $id,
                type: 'POST',
                data: {
                    firstname: $firstname,
                    lastname: $lastname,
                    csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
                },
                success: function(){
                    window.location = '/';
                    alert('Updated!');
                }
            });
        }

    });

    $(document).on('click', '.delete', function(){
        $id = $(this).attr('name');
        $.ajax({
            url: 'delete/' + $id,
            type: 'POST',
            data: {
                csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
            },
            success: function(){
                Read();
                alert("Deleted!");
            }
        });
    });

});

function Read(){
    $.ajax({
  url: 'read',
  type: 'POST',
  async: false,
  data:{
   res: 1,
   csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
  },
  success: function(response){
   $('#result').html(response);
  }
    });
}

Related Post