article

Friday, March 25, 2022

Python Django Inserting Data Using Jquery Ajax

Python Django Inserting Data Using Jquery Ajax

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js


testdev/urls.py
 
//testdev/urls.py
from django.contrib import admin
from django.urls import path
from myapp import views

urlpatterns = [
	path('', views.index, name='index'),
	path('insert', views.insert, name='insert'),
    path('admin/', admin.site.urls),
]
myapp/views.py
 
//myapp/views.py
from django.shortcuts import render, redirect
from .models import Member

# Create your views here.
def index(request):
    members = Member.objects.all()
    return render(request, 'insertajax/index.html', {'members': members})

def insert(request):
    member = Member(firstname=request.POST['firstname'], lastname=request.POST['lastname'], address=request.POST['address'])
    member.save()
    return redirect('/')
myapp/models.py
 
//myapp/models.py
from django.db import models

# Create your models here.
class Member(models.Model):
    firstname = models.CharField(max_length=50)
    lastname = models.CharField(max_length=50)
    address = models.CharField(max_length=50)

    def __str__(self):
        return self.firstname + " " + self.lastname
myapp/templates/insertajax/index.html
 
//myapp/templates/insertajax/index.html
{% extends 'insertajax/base.html' %}
{% block body %}
    <form method="POST">
        {% csrf_token %}
        <div class="mb-3">
            <label>Firstname</label>
               <input type="text" id="firstname" class="form-control"/>
        </div>        
		<div class="mb-3">
            <label>Lastname</label>
            <input type="text" id="lastname" class="form-control"/>
        </div>
        <div class="mb-3">
            <label>Address</label>
            <input type="text" id="address" class="form-control"/>
        </div>
        <div class="mb-3">
            <button type="button" class="btn btn-primary form-control" id="submit" style="width:300px;">Submit</button>
        </div>
    </form>
    <hr style="border-top:1px solid #000; clear:both;"/>
    <table class="table table-bordered">
        <thead class="alert-warning">
            <tr>
                <th>Firstname</th>
                <th>Lastname</th>
                <th>Address</th>
            </tr>
        </thead>
        <tbody>
            {% for member in members %}
            <tr>
                <td>{{ member.firstname }}</td>
                <td>{{ member.lastname }}</td>
                <td>{{ member.address  }}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
{% endblock %}		
myapp/templates/base.html
 
//myapp/templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
	<title>Python Django Inserting Data Using Jquery Ajax </title>
    {% load static %}
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"/>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
</head>
<body>
<div class="container">
    <div class="row">
        <p><h3 class="text-primary">Python Django Inserting Data Using Jquery Ajax</h3></p>
        <hr style="border-top:1px dotted #ccc;"/>
        {% block body %}

        {% endblock %}
    </div>
</div>	
</body>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="{% static 'js/script.js' %}"></script>
</html>
myapp/static/js/script.js
 
//myapp/static/js/script.js
$(document).ready(function(){
    $('#submit').on('click', function(){
        $firstname = $('#firstname').val();
        $lastname = $('#lastname').val();
        $address = $('#address').val();

        if($firstname == "" || $lastname == "" || $address == ""){
            alert("Please complete field");
        }else{
            $.ajax({
                type: "POST",
                url: "insert",
                data:{
                    firstname: $firstname,
                    lastname: $lastname,
                    address: $address,
                    csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
                },
                success: function(){
                    alert('Save Data');
                    $('#firstname').val('');
                    $('#lastname').val('');
                    $('#address').val('');
                    window.location = "/";
                }
            });
        }
    });
});
Register App myapp
devtest/settings.py
 
//devtest/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
	'myapp',
]

migration

C:\my_project_django\testdev>python manage.py makemigrations
C:\my_project_django\testdev>python manage.py migrate

Related Post