article

Wednesday, April 13, 2022

Python Django Ajax Insert Data and Validate Nick Name

Python Django Ajax Insert Data and Validate Nick Name

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.views import (
    indexView,
    postEmployee, 
    checkNickName
)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', indexView),
    path('post/ajax/employee', postEmployee, name = "post_employee"),
    path('get/ajax/validate/nickname', checkNickName, name = "validate_nickname"),
]
myapp/views.py
 
//myapp/views.py
from django.shortcuts import render
from django.http import JsonResponse
from django.core import serializers
from .forms import EmployeeForm
from .models import Employee

def indexView(request):
    form = EmployeeForm()
    empoyees = Employee.objects.all()
    return render(request, "index.html", {"form": form, "empoyees": empoyees})

def postEmployee(request):
    if request.is_ajax and request.method == "POST":
        form = EmployeeForm(request.POST)
        if form.is_valid():
            instance = form.save()
            ser_instance = serializers.serialize('json', [ instance, ])
            return JsonResponse({"instance": ser_instance}, status=200)
        else:
            return JsonResponse({"error": form.errors}, status=400)

    return JsonResponse({"error": ""}, status=400)

def checkNickName(request):
    if request.is_ajax and request.method == "GET":
        nick_name = request.GET.get("nick_name", None)
        if Employee.objects.filter(nick_name = nick_name).exists():
            return JsonResponse({"valid":False}, status = 200)
        else:
            return JsonResponse({"valid":True}, status = 200)

    return JsonResponse({}, status = 400)
myapp/models.py
 
//myapp/models.py
from django.db import models

# Create your models here.
class Employee(models.Model):
    # NICK NAME should be unique
    nick_name = models.CharField(max_length=100, unique =  True)
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    dob = models.DateField(auto_now=False, auto_now_add=False)
    lives_in = models.CharField(max_length=150, null = True, blank = True)

    def __str__(self):
        return self.nick_name
myapp/forms.py
 
//myapp/forms.py
from .models import Employee
from django import forms
import datetime

class EmployeeForm(forms.ModelForm):
    ## change the widget of the date field.
    dob = forms.DateField(
        label='What is your birth date?', 
        # change the range of the years from 1980 to currentYear - 5
        widget=forms.SelectDateWidget(years=range(1980, datetime.date.today().year-5))
    )
    
    def __init__(self, *args, **kwargs):
        super(EmployeeForm, self).__init__(*args, **kwargs)
        ## add a "form-control" class to each form input bootstrap
        for name in self.fields.keys():
            self.fields[name].widget.attrs.update({
                'class': 'form-control',
            })

    class Meta:
        model = Employee
        fields = ("__all__")
myapp/templates/index.html
 
//myapp/templates/index.html	
{% extends 'base.html' %}

{% block body %}
<div class="container-fluid">
  <form id="employee-form">
        <div class="row">
            {% csrf_token %}
            {% for field in form %}
            <div class="form-group col-4">
                <label class="col-12">{{ field.label }}</label>
                {{ field }}
            </div>
            {% endfor %}
        </div>
        <div class="row" style="margin:20px;">
            <input type="submit" class="btn btn-primary" value="Create Employee" style="width:300px;"/>
        </div>
  <form>
</div>

<hr />

<div class="container-fluid">
    <table class="table table-striped table-sm" id="my_employee">
        <thead>
            <tr>
                <th>Nick name</th>
                <th>First name</th>
                <th>Last name</th>
                <th>DOB</th>
                <th>Address</th>
            </tr>
        </thead>
        <tbody>
        {% for rs in empoyees %}
        <tr>
            <td>{{rs.nick_name}}</td>
            <td>{{rs.first_name}}</td>
            <td>{{rs.last_name}}</td>
            <td>{{rs.dob | date:"Y-m-d"}}</td>
            <td>{{rs.lives_in}}</td>
        </tr>
        {% endfor %}
        </tbody>
    </table>

</div>
{% endblock %}
myapp/templates/base.html
 
//myapp/templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Python Django Ajax Insert Data and Validate Nick Name</title>
    <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 Ajax Insert Data and Validate Nick Name</h3></p>
            <hr style="border-top:1px dotted #ccc;"/>
            {% block body %}
      
            {% endblock %}
        </div>
    </div> 
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script>
$(document).ready(function () {

            $("#employee-form").submit(function (e) {
                e.preventDefault();
                var serializedData = $(this).serialize();
                $.ajax({
                    type: 'POST',
                    url: "{% url 'post_employee' %}",
                    data: serializedData,
                    success: function (response) {
                        $("#employee-form").trigger('reset'); // clear the form.
                        $("#id_nick_name").focus(); // focus to nickname input 
    
                        var instance = JSON.parse(response["instance"]);
                        var fields = instance[0]["fields"];
                        $("#my_employee tbody").prepend(
                            `<tr>
                            <td>${fields["nick_name"]||""}</td>
                            <td>${fields["first_name"]||""}</td>
                            <td>${fields["last_name"]||""}</td>
                            <td>${fields["dob"]||""}</td>
                            <td>${fields["lives_in"]||""}</td>
                            </tr>`
                        )
                    },
                    error: function (response) {
                        alert(response["responseJSON"]["error"]); // alert the error if any error occured
                    }
                })
            })
    
            $("#id_nick_name").focusout(function (e) {
                e.preventDefault();
                var nick_name = $(this).val();
                $.ajax({
                    type: 'GET',
                    url: "{% url 'validate_nickname' %}",
                    data: {"nick_name": nick_name},
                    success: function (response) {
                        if(!response["valid"]){ // if not valid user, alert the user
                            alert("You cannot create a Employee with same nick name");
                            var nickName = $("#id_nick_name");
                            nickName.val("")
                            nickName.focus()
                        }
                    },
                    error: function (response) {
                        console.log(response)
                    }
                })
            })
})
</script>
</body>
</html>
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