article

Friday, May 1, 2020

Python Django Inserting Data Using Jquery Ajax


Python Django Inserting Data Using Jquery Ajax


 
#views.py
from django.shortcuts import render, redirect
from myapp.models import Member

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

def insert(request):
    member = Member(firstname=request.POST['firstname'], lastname=request.POST['lastname'], address=request.POST['address'], username=request.POST['username'])
    member.save()
    return redirect('/')
 
#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)
    username = models.CharField(max_length=50)
 
    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'^insert$', views.insert, name='insert'),
] 
//templates/index.html
{% extends 'base.html' %}
{% block body %}
    <form class="" method="post">
        {% csrf_token %}
        <div class="form-inline">
            <label>UserName</label>
            <input type="text" id="username" name="username" class="form-control"/>
        </div>
  <br />
  <div class="form-inline">
            <label>Firstname</label>
               <input type="text" id="firstname" name="firstname" class="form-control"/>
            <label>Lastname</label>
            <input type="text" id="lastname" name="lastname" class="form-control"/>
        </div>
        <br />
        <div class="form-group">
            <label>Address</label>
            <input type="text" id="address" name="address" class="form-control"/>
        </div>
        <div class="col-md-4"></div>
        <div class="col-md-4 form-group">
    <button type="button" class="btn btn-primary form-control" id="submit">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 %}
//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"/>
 <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
 <script src="{% static 'js/script.js' %}"></script>
</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 Inserting Data Using Jquery Ajax</h3>
        <hr style="border-top:1px dotted #ccc;"/>
        {% block body %}

        {% endblock %}
    </div>
</body>
</html>
//static/js/script.js
$(document).ready(function(){
    $('#submit').on('click', function(){
        $firstname = $('#firstname').val();
        $lastname = $('#lastname').val();
        $address = $('#address').val();
        $username = $('#username').val();
 
        if($firstname == "" || $lastname == "" || $address == "" || $username == ""){
            alert("Please complete field");
        }else{
            $.ajax({
                type: "POST",
                url: "insert",
                data:{
                    firstname: $firstname,
                    lastname: $lastname,
                    address: $address,
                    username: $username,
                    csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
                },
                success: function(){
                    alert('Save Data');
                    $('#firstname').val('');
                    $('#lastname').val('');
                    $('#address').val('');
                    $('#username').val('');
                    window.location = "/";
                }
            });
        }
    });
});

Related Post