article

Thursday, April 30, 2020

Django Jquery Ajax Check Username before Inserting Data


Django Jquery Ajax Check Username before Inserting Data

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

# 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('/')


def validate_username(request):
    username = request.GET.get('username', None)
    data = {
        'is_taken': Member.objects.filter(username=username).exists()
    }
    if data['is_taken']:
        data['error_message'] = 'A user with this username already exists.'
    return JsonResponse(data)
#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),
    path('insert/',views.insert),
    url(r'^validate_username/$', views.validate_username, name='validate_username'),
] 
//templates/index.html
{% extends 'base.html' %}
{% block body %}
    <form class="" action="/insert/" 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">
    <input type="submit" class="btn btn-primary form-control" name="" value="Submit">
        </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">Django Jquery Ajax Check Username before Inserting Data</h3>
        <hr style="border-top:1px dotted #ccc;"/>
        {% block body %}

        {% endblock %}
    </div>
</body>
</html>
//static/js/script.js
$(document).ready(function(){
    $("#username").change(function () {
      var username = $(this).val();

      $.ajax({
        url: '/validate_username/',
        data: {
          'username': username
        },
        dataType: 'json',
        success: function (data) {
          if (data.is_taken) {
            alert("A user with this username already exists.");
          }
        }
      });

    });
});

Related Post