article

Showing posts with label Python-Django. Show all posts
Showing posts with label Python-Django. Show all posts

Wednesday, May 18, 2022

Django Mysql CRUD (Create Read Update Delete) with Datatables

Django Mysql CRUD (Create Read Update Delete) with Datatables

Register App myapp and
Connect to MySQL Database

devproject/settings.py
 
//devproject/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp', #add myapp
]
      
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '3306'
    }
}
Create Model
myapp/models.py
 
//myapp/models.py
from django.db import models

# Create your models here.
class Employee(models.Model):  
    name = models.CharField(max_length=100)  
    email = models.EmailField()  
    contact = models.CharField(max_length=15) 
  
    class Meta:  
        db_table = "tblemployee"
Make Migrations
Run the commands below to make migrations:
python manage.py makemigrations
python manage.py migrate
C:\django\devproject>python manage.py makemigrations
C:\django\devproject>python manage.py migrate

Create Forms
myapp/forms.py
 
//myapp/forms.py
from django import forms  
from myapp.models import Employee  
class EmployeeForm(forms.ModelForm):  
    class Meta:  
        model = Employee  
        fields = ['name', 'contact', 'email'] 
        widgets = { 'name': forms.TextInput(attrs={ 'class': 'form-control' }), 
            'email': forms.EmailInput(attrs={ 'class': 'form-control' }),
            'contact': forms.TextInput(attrs={ 'class': 'form-control' }),
      }
Creating View
myapp/views.py
 
//myapp/views.py
from django.shortcuts import render, redirect  
from myapp.forms import EmployeeForm  
from myapp.models import Employee  

# Create your views here.  
def addnew(request):  
    if request.method == "POST":  
        form = EmployeeForm(request.POST)  
        if form.is_valid():  
            try:  
                form.save()  
                return redirect('/')  
            except:  
                pass 
    else:  
        form = EmployeeForm()  
    return render(request,'index.html',{'form':form})  

def index(request):  
    employees = Employee.objects.all()  
    return render(request,"show.html",{'employees':employees})  

def edit(request, id):  
    employee = Employee.objects.get(id=id)  
    return render(request,'edit.html', {'employee':employee})  

def update(request, id):  
    employee = Employee.objects.get(id=id)  
    form = EmployeeForm(request.POST, instance = employee)  
    if form.is_valid():  
        form.save()  
        return redirect("/")  
    return render(request, 'edit.html', {'employee': employee})  
    
def destroy(request, id):  
    employee = Employee.objects.get(id=id)  
    employee.delete()  
    return redirect("/")  
Template

myapp/templates/index.html

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

https://datatables.net/
DataTables is a powerful jQuery plugin for creating table listings and adding interactions to them. It provides searching, sorting and pagination without any configuration.

myapp/templates/base.html
//myapp/templates/base.html
<!DOCTYPE html>  
<html lang="en">  
<head>  
<meta charset="UTF-8">  
<title>{% block title %}{% endblock %}</title>
{% load static %}  
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"/>
<link rel = "stylesheet" type = "text/css" href = "https://cdn.datatables.net/1.12.0/css/jquery.dataTables.min.css"/>
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
</head> 
<body>
<div class="container">
 <div class="row">
    <h4>Django Mysql CRUD (Create Read Update Delete) with Datatables</h4> 
    {% block content %}{% endblock %}
 </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
<script src = "https://cdn.datatables.net/1.12.0/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function() {
    $('#bootstrapdatatable').DataTable({     
      "aLengthMenu": [[3, 5, 10, 25, -1], [3, 5, 10, 25, "All"]],
        "iDisplayLength": 3
       } 
    );
} );
</script>
</body> 
</html>
myapp/templates/show.html
//myapp/templates/show.html
{% extends "base.html" %}
 
{% block title %}Employee Records{% endblock title %}
 
{% block content %}
 <div class="col-md-12">
        <span><a href="/addnew" class="btn btn-primary">Add New Record</a></span>  
        <div class="table-responsive">
        <table id="bootstrapdatatable" class="table table-striped table-bordered" width="100%">
        <thead>
            <th><input type="checkbox" id="checkall" /></th>
            <th>ID</th>
            <th>Employee Name</th>
            <th>Employee Email</th>
            <th>Employee Contact</th>
            <th>Edit</th>
            <th>Delete</th>
        </thead>
        <tbody>
        {% for employee in employees %}  
            <tr>  
            <td><input type="checkbox" class="checkthis" /></td>
            <td>{{ employee.id }}</td>  
            <td>{{ employee.name }}</td>  
            <td>{{ employee.email }}</td>  
            <td>{{ employee.contact }}</td>  
            <td><a href="/edit/{{ employee.id }}" class="btn btn-primary">Edit</a></td>
            <td><a href="/delete/{{ employee.id }}" class="btn btn-danger">Delete</a></td>  
            </tr>  
        {% endfor %} 
        </tbody>
        </table>
        </div>
    </div>
{% endblock content %}
myapp/templates/index.html
//myapp/templates/index.html
{% extends "base.html" %}
 
{% block title %}Add New Employee Records{% endblock title %}
 
{% block content %}
<div class="col-md-12">    
    <form method="POST" class="post-form" action="/addnew">  
    {% csrf_token %}  
    <div class="container">  
        <div class="col-12">  
        <h3>Enter Details</h3>  
        </div>    
    
        <div class="mb-3"> 
            <label>Name:</label>  
            {{ form.name }}   
        </div> 
        <div class="mb-3"> 
            <label>Email:</label>  
            {{ form.email }}   
        </div>  
        <div class="mb-3"> 
            <label>Contact:</label>  
            {{ form.contact }}   
        </div>
        <div class="mb-3"> 
            <button type="submit" class="btn btn-primary">Submit</button>    
        </div> 
    </div>  
    </form>  
</div> 
{% endblock content %} 
myapp/templates/edit.html
//myapp/templates/edit.html
{% extends "base.html" %}
 
{% block title %}Add New Employee Records{% endblock title %}
 
{% block content %}
<div class="col-md-12">
    <form method="POST" class="post-form" action="/update/{{employee.id}}">  
    {% csrf_token %}  
    <div class="container">   
        <div class="col-12">  
            <h3>Update Details</h3>  
        </div> 
        <div class="mb-3"> 
            <label>Employee ID:</label>  
            <input type="text" class="form-control" name="id" id="id_id" required maxlength="20" value="{{ employee.id }}"/>    
        </div> 
        <div class="mb-3"> 
            <label>Name:</label>  
            <input type="text" class="form-control" name="name" id="id_name" required maxlength="100" value="{{ employee.name }}" />  
        </div> 
        <div class="mb-3"> 
            <label>Email:</label>  
            <input type="email" class="form-control" name="email" id="id_email" required maxlength="254" value="{{ employee.email }}" />  
        </div> 
        <div class="mb-3"> 
            <label>Contact:</label>  
            <input type="text" class="form-control" name="contact" id="id_contact" required maxlength="15" value="{{ employee.contact }}" />  
        </div> 
        <div class="mb-3"> 
            <button type="submit" class="btn btn-success btn-lg">Update</button>  
        </div> 
    </div>  
    </form>  
{% endblock content %}   
URL
devproject/urls.py

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='index'),  
    path('addnew',views.addnew, name='addnew'),  
    path('edit/<int:id>', views.edit, name='edit'),  
    path('update/<int:id>', views.update, name='update'),  
    path('delete/<int:id>', views.destroy, name='destroy'),  
]
Run : C:\django\devproject>python manage.py runserver

Saturday, May 14, 2022

Python Django Mysql CRUD (Create, Read, Update and Delete) with Jquery Ajax

Python Django Mysql CRUD (Create, Read, Update and Delete) with Jquery Ajax

Register App myapp and
Connect to MySQL Database

devproject/settings.py
 
//devproject/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp', #add myapp
]
     
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '3306'
    }
}
Create Model
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)
   
    class Meta:  
        db_table = "tbl_member"
Make Migrations
Run the commands below to make migrations:
python manage.py makemigrations
python manage.py migrate
C:\django\devproject>python manage.py makemigrations
C:\django\devproject>python manage.py migrate

Creating View
myapp/views.py
 
//myapp/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('/')
Template

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
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js

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

myapp/templates/index.html
//myapp/templates/index.html
{% extends 'base.html' %}
{% block body %}
<form class="form-inline">
    {% csrf_token %}
    <div class="mb-3">
        <label>Firstname</label>
        <input type="text" id="firstname" class="form-control" style="width:30%;" required="required"/>
    </div>    
    <div class="mb-3">
        <label>Lastname</label>
        <input type="text" id="lastname" class="form-control" style="width:30%;" required="required"/>
    </div>
    <div class="mb-3">    
        <button type="button" id="create" class="btn btn-primary">Create</button>
    </div>
</form>
<br />
<div id="result"></div>
{% endblock %}
myapp/templates/base.html
//myapp/templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
{% load static %}
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"/>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</head>
<body>
    <div class="container">
        <header>
            <h1>Python Django Mysql CRUD (Create, Read, Update and Delete) with Jquery Ajax</h1>
        </header>
        <hr>
        <main>
            {% block body %}
            {% endblock %}
        </main>
        <hr>
    </div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="{% static 'js/script.js' %}"></script>
</body>
</html>
myapp/templates/edit.html
//myapp/templates/edit.html
{% extends 'base.html' %}
{% block body %}
    <form>
        {% csrf_token %}
        <input type="hidden" id="member_id" value="{{ member.id }}"/>
        <div class="mb-3">
            <label>Firstname</label>
            <input type="text" id="firstname" value="{{ member.firstname }}" class="form-control" required="required"/>
        </div>
        <div class="mb-3">
            <label>Lastname</label>
            <input type="text" id="lastname" value="{{ member.lastname }}" class="form-control" required="required"/>
        </div>
        <div class="mb-3">
            <button type="button" id="update" class="btn btn-warning">Update</button>
        </div>
    </form>
{% endblock %}
myapp/templates/result.html
//myapp/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-warning edit" name="{{ member.id }}">Edit</a> 
                <a class="btn btn-danger delete" name="{{ member.id }}">Delete</a></center>
            </td>
        </tr>
        {% endfor %}
    </tbody>
</table>
myapp/static/js/script.js
//myapp/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('');
                    alert("New Member Successfully Added");
                }
            });
        }
    });
 
    $(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);
        }
    });
}
URL
devproject/urls.py
//devproject/urls.py
from django.contrib import admin
from django.urls import path
from myapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='index'),
    path('create/',views.create, name='create'),
    path('read/',views.read, name='read'),
    path('edit/<id>',views.edit, name='edit'),
    path('edit/update/<id>',views.update, name='update'),
    path('delete/<id>',views.delete, name='delete'),
]
Run : C:\django\devproject>python manage.py runserver

Wednesday, May 11, 2022

Django Mysql Insert Data Using Jquery Ajax

Django Mysql Insert 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
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js

Register App myapp and
Connect to MySQL Database

devproject/settings.py
 
//devproject/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp', #add myapp
]
    
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '3306'
    }
}
Create Model
 
//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)
    username = models.CharField(max_length=50)
  
    class Meta:  
        db_table = "blog_member"
Make Migrations
Run the commands below to make migrations:
python manage.py makemigrations
python manage.py migrate
C:\django\devproject>python manage.py makemigrations
C:\django\devproject>python manage.py migrate

Creating View
myapp/views.py
 
//myapp/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('/')
Template myapp/templates/index.html
 
//myapp/templates/index.html
{% extends 'base.html' %}
{% block body %}

    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addnew">
      Add New
    </button>

    <!-- Modal -->
    <div class="modal fade" id="addnew" tabindex="-1" aria-labelledby="addnewLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="addnewLabel">New Member</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-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>
              <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>
              <div class="form-group">
                  <label>Address</label>
                  <input type="text" id="address" name="address" class="form-control"/>
              </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary" id="submit">Submit</button>
          </form>
          </div>
        </div>
      </div>
    </div>

    <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>
{% load static %}
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"/>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="{% static 'js/script.js' %}"></script>
</head>
<body>
  <div class="container">
  <header>
    <h1>Django Mysql Insert Data Using Jquery Ajax</h1>
  </header>
  <hr>
  <main>
    {% block body %}
    {% endblock %}
  </main>
  <hr>
  </div>
</body>
</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();
        $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 = "/";
                }
            });
        }
    });
});
URL
devproject/urls.py
//devproject/urls.py
from django.contrib import admin
from django.urls import path
from myapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='index'),
    path('insert/',views.insert, name='insert'),
]
Run : C:\django\devproject>python manage.py runserver

Thursday, May 5, 2022

Django Mysql User Authentication - Login, register and Logout

Django Mysql User Authentication - Login, register and Logout

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

Register App myapp and
Connect to MySQL Database

devproject/settings.py
//devproject/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp', #add myapp
]
   
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '3306'
    }
}
Make Migrations
Run the commands below to make migrations:
python manage.py makemigrations
python manage.py migrate
C:\django\devproject>python manage.py makemigrations
C:\django\devproject>python manage.py migrate
Creating View
myapp/views.py
//myapp/views.py
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import logout
from django.shortcuts import HttpResponseRedirect
 
def signup(request):
    if request.user.is_authenticated:
        return redirect('/')
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=password)
            login(request, user)
            return redirect('/')
        else:
            return render(request, 'signup.html', {'form': form})
    else:
        form = UserCreationForm()
        return render(request, 'signup.html', {'form': form})
  
def home(request): 
    return render(request, 'home.html')
  
 
def signin(request):
    if request.user.is_authenticated:
        return render(request, 'home.html')
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return redirect('/profile') #profile
        else:
            msg = 'Error Login'
            form = AuthenticationForm(request.POST)
            return render(request, 'login.html', {'form': form, 'msg': msg})
    else:
        form = AuthenticationForm()
        return render(request, 'login.html', {'form': form})
 
def profile(request): 
    return render(request, 'profile.html')
  
def signout(request):
    logout(request)
    return redirect('/')
devproject/urls.py
//devproject/urls.py
from django.contrib import admin
from django.urls import path
from myapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.home, name='home'),
    path('signin/',views.signin, name='signin'),
    path('signout/',views.signout, name='signout'),
    path('signup/',views.signup, name='signup'),
    path('profile/',views.profile, name='profile'),
]
myapp/templates/index.html
//myapp/templates/home.html
{% extends 'base.html' %}
 
{% block title %}Login{% endblock %}
 
{% block content %}
   <h2>Welcome!</h2>
   {% if user.is_authenticated %}
      Hi {{ user.username }}!
      <a href="/signout" class="btn btn-danger">Logout</a>
    {% else %}
      <a href="/signin" class="btn btn-primary"><span class="glyphicon glyphicon-log-in"></span>Login</a> 
      <a href="/signup" class="btn btn-success">Signup</a>
    {% endif %}
{% endblock %}
myapp/templates/base.html
//myapp/templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>{% block title %}Django Mysql User Authentication - Login, register and Logout{% endblock %}</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">
  <header>
    <h1>Django Mysql User Authentication - Login, register and Logout</h1>
  </header>
  <hr>
  <main>
    {% block content %}
    {% endblock %}
  </main>
  <hr>
  </div>
</body>
</html>
myapp/templates/login.html
//myapp/templates/login.html
{% extends 'base.html' %}
 
{% block title %}Login{% endblock %}
 
{% block content %}
  <h2>Login</h2> {{ msg }}
  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" class="btn btn-primary">Login</button>
  </form>
{% endblock %}
myapp/templates/signup.html
//myapp/templates/signup.html
{% extends 'base.html' %}
 
{% block content %}
  <h2>Sign up</h2>
  <form method="post">
    {% csrf_token %}
    {% for field in form %}
      <p>
        {{ field.label_tag }}<br>
        {{ field }}
        {% for error in field.errors %}
          <p style="color: red">{{ error }}</p>
        {% endfor %}
      </p>
    {% endfor %}
    <button type="submit" class="btn btn-success">Sign up</button>
  </form>
{% endblock %}
myapp/templates/profile.html
//myapp/templates/profile.html
{% extends 'base.html' %}
 
{% block title %}Login{% endblock %}
 
{% block content %}
   <h2>Welcome!</h2>
   {% if user.is_authenticated %}
      Hi {{ user.username }}!
      <a href="/signout" class="btn btn-danger">Logout</a>
    {% else %}
      <a href="/signin" class="btn btn-primary"><span class="glyphicon glyphicon-log-in"></span>Login</a> 
      <a href="/signup" class="btn btn-success">Signup</a>
    {% endif %}
{% endblock %}
Run : C:\django\devproject>python manage.py runserver

Friday, April 29, 2022

Python Django Pagination Mysql with Bootstrap 5

Python Django Pagination Mysql with Bootstrap 5

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

CREATE TABLE `employee` (
  `id` bigint(20) NOT NULL,
  `name` varchar(100) NOT NULL,
  `email` varchar(254) NOT NULL,
  `contact` varchar(15) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT INTO `employee` (`id`, `name`, `email`, `contact`) VALUES
(1, 'Cairocoders', 'cairocoders@gmail.com', '35345345'),
(2, 'clydey Ednalan', 'calyde@gmail.com', '6456'),
(3, 'Airi Satou', 'Airi Satou@gmail.com', '45345435'),
(4, 'Angelica Ramos', 'Angelica Ramos', '435345345'),
(5, 'Ashton Cox', 'Ashton Cox@gmail.com', '35345345'),
(6, 'Bradley Greer', 'Bradley Greer', '3453453'),
(7, 'Brenden Wagner', 'Brenden Wagner@gmail.com', '5656'),
(8, 'Brielle Williamson', 'Brielle Williamson@gmail.com', '56456'),
(9, 'Bruno Nash', 'Bruno Nash@gmail.com', '456456'),
(10, 'Caesar Vance', 'Caesar Vance@gmail.com', '45345'),
(11, 'Cara Stevens', 'Cara Stevens@gmail.com', 'ertert'),
(12, 'Cedric Kelly', 'Cedric Kelly@gmail.com', '565656'),
(13, 'Charde Marshall', 'Charde Marshall@gmail.com', '67567'),
(14, 'Colleen Hurst', 'Colleen Hurst@gmail.com', '979789'),
(15, 'Dai Rios', 'Dai Rios@gmail.com', '7868678'),
(16, 'Donna Snider', 'Donna Snider@gamil.com', '77868');
Register App myapp and
Connect to MySQL Database
devproject/settings.py
 
//devproject/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp', #add myapp
]
  
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '3306'
    }
}
Model
myapp/models.py
 
//myapp/models.py
from django.db import models
 
# Create your models here.
class Employee(models.Model):  
    name = models.CharField(max_length=100)  
    email = models.EmailField()  
    contact = models.CharField(max_length=15) 
  
    class Meta:  
        db_table = "employee"
Make Migrations
Run the commands below to make migrations:
python manage.py makemigrations
python manage.py migrate
C:\django\devproject>python manage.py makemigrations
C:\django\devproject>python manage.py migrate
Creating View
myapp/views.py
 
//myapp/views.py
from django.shortcuts import render, redirect  
from myapp.models import Employee  #models.py
 
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
# Create your views here.   

def index(request):
    emplist = Employee.objects.all() 
    page = request.GET.get('page', 1)
 
    paginator = Paginator(emplist, 5)
    try:
        employees = paginator.page(page)
    except PageNotAnInteger:
        employees = paginator.page(1)
    except EmptyPage:
        employees = paginator.page(paginator.num_pages)
 
    return render(request, 'index.html', { 'employees': employees })
devproject/urls.py
 
//devproject/urls.py
from django.contrib import admin
from django.urls import path
from myapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='index')
]
myapp/templates/index.html
 
//myapp/templates/index.html
<!DOCTYPE html>  
<html lang="en">  
<head>  
<meta charset="UTF-8">  
<title>Python Django Pagination Mysql with  Bootstrap 5</title> 
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
</head> 
<body>
<div class="container">
  <div class="row">
      <div class="col-12">
          <h2>Python Django Pagination Mysql with  Bootstrap 5</h2>  
          <h4>Employees</h4>  
        <table id="bootstrapdatatable" class="table table-striped table-bordered" width="100%">
          <thead>
            <tr>
              <th>Name</th>
              <th>Contact</th>
              <th>Email</th>
            </tr>
          </thead>
          <tbody>
            {% for rs_emp in employees %}
              <tr>
              <td>{{ rs_emp.name }}</td>
              <td>{{ rs_emp.contact }}</td>
              <td>{{ rs_emp.email }}</td>
              </tr>
            {% endfor %}
          </tbody>
        </table>
      
      <nav aria-label="...">
      {% if employees.has_other_pages %}
        <ul class="pagination">
          {% if employees.has_previous %}
            <li class="page-item"><a class="page-link" href="?page={{ employees.previous_page_number }}">Previous</a></li>
          {% else %}
            <li class="page-item disabled"><span class="page-link">Previous</span></li>
          {% endif %}

          {% for i in employees.paginator.page_range %}
            {% if employees.number == i %}
            <li class="page-item active" aria-current="page"><a class="page-link" href="#">{{ i }}</a></li>
            {% else %}
            <li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li>
            {% endif %}
          {% endfor %}

          {% if employees.has_next %}
            <li class="page-item"><a class="page-link" href="?page={{ employees.next_page_number }}">Next</a></li>
          {% else %}
            <li class="page-item disabled"><span class="page-link">Next</span></li>
          {% endif %}
        </ul>
      {% endif %}
      </nav>

    </div>        
  </div> 
</div> 
</body> 
</html>
Run : C:\django\devproject>python manage.py runserver

Thursday, April 28, 2022

Django File Upload Save to Mysql Database

Django File Upload Save to Mysql Database

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

Mysql tabase table
CREATE TABLE `student` (
  `id` bigint(20) NOT NULL,
  `firstname` varchar(50) NOT NULL,
  `lastname` varchar(50) NOT NULL,
  `email` varchar(254) NOT NULL,
  `file` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Register App myapp and
Connect to MySQL Database
//devproject/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp', #add myapp
]
 
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '3306'
    }
}
Model
myapp/models.py
//myapp/models.py
from django.db import models

# Create your models here.
class StudentForm(models.Model):  
    firstname = models.CharField("Enter first name", max_length=50)  
    lastname  = models.CharField("Enter last name", max_length = 50)  
    email     = models.EmailField("Enter Email")  
    file      = models.FileField() # for creating file input  
  
    class Meta:  
        db_table = "student"
Make Migrations
Run the commands below to make migrations:
python manage.py makemigrations
python manage.py migrate
C:\my_project_django\testdev>python manage.py makemigrations
C:\my_project_django\testdev>python manage.py migrate
Creating View
myapp/views.py
 
//myapp/views.py
from django.shortcuts import render
from django.http import HttpResponse  
from myapp.functions import handle_uploaded_file  #functions.py
from myapp.forms import StudentForm #forms.py
  
def index(request):  
    if request.method == 'POST':  
        student = StudentForm(request.POST, request.FILES)  
        if student.is_valid():  
            handle_uploaded_file(request.FILES['file'])  
            model_instance = student.save(commit=False)
            model_instance.save()
            return HttpResponse("File uploaded successfuly")  
    else:  
        student = StudentForm()  
        return render(request,"index.html",{'form':student}) 
myapp/forms.py
 
////myapp/forms.py
from django import forms  
from myapp.models import StudentForm  #models.py
    
class StudentForm(forms.ModelForm):  
    class Meta:  
        model = StudentForm  
        fields = "__all__"

    def __init__(self, *args, **kwargs):
            super(StudentForm, self).__init__(*args, **kwargs)
            for field_name, field in self.fields.items():
                field.widget.attrs['class'] = 'form-control'	
myapp/functions.py
 
//myapp/functions.py
def handle_uploaded_file(f):  
    with open('myapp/static/upload/'+f.name, 'wb+') as destination:  
        for chunk in f.chunks():  
            destination.write(chunk) 
myapp/urls.py
 
//myapp/urls.py
from django.contrib import admin
from django.urls import path
from myapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='index')
]			
myapp/templates/index.html
//myapp/templates/index.html
<html>
<head>
<title>Django File Upload - cairocoders</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container" style="padding:20px;">
    <div class="row">
        <div class="col-12">
            <p><h1>Django File Upload Save to Mysql Database</h1></p>
            <form method="POST" class="post-form" enctype="multipart/form-data">  
                    {% csrf_token %}  
                    {{ form.as_p }}  
                <button type="submit" class="btn btn-primary">Save</button>  
            </form>  
        </div>
    </div>
</div>
</body>  
</html>
Run : C:\django\devproject>python manage.py runserver

Tuesday, April 26, 2022

Python Django How to setup MySQL Databse with DataTables

Python Django How to setup MySQL Databse with DataTables

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

Datatables
https://datatables.net/
DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, built upon the foundations of progressive enhancement, that adds all of these advanced features to any HTML table.

Register App myapp and
Connect to MySQL Database

devtest/settings.py
 
//devproject/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp', #add myapp
]

DATABASES = {
    'default': {
		'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django',
		'USER': 'root',
		'PASSWORD': '',
		'HOST': 'localhost',
		'PORT': '3306'
    }
}
Model Class
 
//myapp/models.py
from django.db import models

# Create your models here.
class User(models.Model):
	id = models.IntegerField()
	name = models.CharField(max_length=50)
	email = models.CharField(max_length=100)
	phone = models.IntegerField(max_length=10)
	address = models.CharField(max_length=250)
	
	class Meta:  
		db_table = "user"
		app_label = ''
	
	def __str__(self):
		return self
database user table
 
//database user table
CREATE TABLE `user` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `email` varchar(100) NOT NULL,
  `phone` int unsigned NOT NULL,
  `address` varchar(250) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

insert  into `user`(`id`,`name`,`email`,`phone`,`address`) values 
(1,'cairocoders','cairocoders@gmail.com',2147483647,'Olongapo City'),
(2,'tutorial101','turorial101@gmail.com',34256780,'Olongapo City');
Make Migrations
Run the commands below to make migrations:
python manage.py makemigrations
python manage.py migrate
C:\my_project_django\testdev>python manage.py makemigrations
C:\my_project_django\testdev>python manage.py migrate
Creating View
myapp/views.py
 
//myapp/views.py
from django.http import HttpResponse
from django.template import loader
from django.shortcuts import render

from .models import User


def index(request):
	user_list = User.objects.order_by('id')
	
	#template = loader.get_template('index.html')
	
	#context = {
    #    'user_list': user_list,
    #}
    
	#return HttpResponse(template.render(context, request))
	
	context = {'user_list': user_list}
	return render(request, 'index.html', context)
myapp/urls.py
 
//myapp/urls.py
from django.contrib import admin
from django.urls import path
from myapp import views #add myapp

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='index')
]
myapp/templates/index.html
//myapp/templates/index.html
{% extends "base.html" %}

{% block content %}
{% if user_list %}
	<table id="table" class="table table-bordered table-striped">
		<thead>
			<th>Id</th>
			<th>Name</th>
			<th>Email</th>
			<th>Phone</th>
			<th>Address</th>
		</thead>
		<tbody>
		{% for user in user_list %}
			<tr>
				<td>{{user.id}}</td>
				<td>{{user.name}}</td>
				<td>{{user.email}}</td>
				<td>{{user.phone}}</td>
				<td>{{user.address}}</td>
			</tr>
		{% endfor %}
		</tbody>
    </table>
{% else %}
    <p>No user record available</p>
{% endif %}
{% endblock %}
myapp/templates/base.html
 
//myapp/templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
<title>Python Django How to setup MySQL Databse</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
<link rel = "stylesheet" type = "text/css" href = "https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css"/>
</head>
<body>
<div class="container" style="padding:20px;">
    <div class="col-12">
        <h3 class="text-primary">Python Django How to setup MySQL Databse with DataTables</h3> 
        <hr style="border-top:1px dotted #ccc;"/>
        {% block content %} {% endblock %}
    </div>
</div>	
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src = "https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script type = "text/javascript">
$(document).ready(function(){
    $('#table').DataTable();
});
</script>
</body>
</html>
Run : C:\django\devproject>python manage.py runserver

Sunday, April 24, 2022

Python Django Simple CRUD (Create, Read, Update and Delete)

Python Django Simple CRUD (Create, Read, Update and Delete)

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
testdev/urls.py
 
//testdev/urls.py
from django.contrib import admin
from django.urls import path, include #add include
 
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls')), #add this line
]
myapp/urls.py
//myapp/urls.py
from django.urls import path
from . import views
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<int:pk>/', views.PostDetailView.as_view(), name='detail'),
    path('edit/<int:pk>/', views.edit, name='edit'),
    path('post/', views.postview, name='post'),
    path('delete/<int:pk>/', views.delete, name='delete'),
]
myapp/views.py
 
//myapp/views.py
from django.shortcuts import render, redirect, get_object_or_404
from .forms import PostForm
from .models import Post
from django.views.generic import ListView, DetailView

class IndexView(ListView):
    template_name='crud/index.html'
    context_object_name = 'post_list'

    def get_queryset(self):
        return Post.objects.all()

class PostDetailView(DetailView):
    model=Post
    template_name = 'crud/post-detail.html'

def postview(request):
    if request.method == 'POST':
        form = PostForm(request.POST)

        if form.is_valid():
            form.save()
            return redirect('index')

    form = PostForm()
    return render(request,'crud/post.html',{'form': form})

def edit(request, pk, template_name='crud/edit.html'):
    post= get_object_or_404(Post, pk=pk)
    form = PostForm(request.POST or None, instance=post)
    if form.is_valid():
        form.save()
        return redirect('index')
    return render(request, template_name, {'form':form})

def delete(request, pk, template_name='crud/confirm_delete.html'):
    post= get_object_or_404(Post, pk=pk)    
    if request.method=='POST':
        post.delete()
        return redirect('index')
    return render(request, template_name, {'object':post})
myapp/models.py
 
//myapp/models.py
from django.db import models

# Create your models here.
class Post(models.Model):
    title = models.CharField(max_length=120, help_text='title of message.')
    message = models.TextField(help_text="what's on your mind ...")
 
    def __str__(self):
        return self.title
Make Migrations
Run the commands below to make migrations:
python manage.py makemigrations
python manage.py migrate
C:\my_project_django\testdev>python manage.py makemigrations
C:\my_project_django\testdev>python manage.py migrate
Table Created Check Database table
myapp/forms.py
 
//myapp/forms.py
from django import forms
from .models import Post

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = "__all__"
myapp/templates/crud/base.html
 
//myapp/templates/crud/base.html
<!DOCTYPE html>
<html>
<head>
<title>CRUD app</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
</head>
<body>
{% block content %} {% endblock %}
</body>
</html>	
myapp/templates/crud/index.html
 
//myapp/templates/crud/index.html
{% extends 'crud/base.html' %}

{% block content %}
<div class="container">
	<div class="row">
		<h1>Python Django CRUD (Create, Read, Update and Delete)</h1>
	</div>
    <div class="row">
        <div class="col-md-12">
            <h2>Post Table
				<a href="{% url 'post' %}"><button type="button" class="btn btn-success">Add New</button></a>
            </h2>
            <table class="table table-bordered table-striped">
                <thead>
                    <th>Title</th>
                    <th>Action</th>
                </thead>
                <tbody>
					{% for post in post_list %}
                        <tr>
                            <td><a href="{% url 'detail' post.pk %}">{{ post.title }}</a>  <span class="badge"></span></td>
                            <td>
								<a href="{% url 'detail' post.pk %}"><button type="button" class="btn btn-info">View</button></a> |
								<a href="{% url 'edit' post.pk %}"><button type="button" class="btn btn-info">Edit</button></a> |
								<a href="{% url 'delete' post.pk %}"><button type="button" class="btn btn-danger">Delete</button></a>
							</td>
                        </tr>
					{% endfor %}	
                </tbody>
            </table>
        </div>
    </div>
</div>
{% endblock %}
we will be using django-widget-tweaks install it https://pypi.org/project/django-widget-tweaks/
pip install django-widget-tweaks
C:\my_project_django\testdev>pip install django-widget-tweaks
open settings.py INSTALLED_APPS section and add widget_tweaks myapp/templates/crud/post.html
 
//myapp/templates/crud/post.html
{% extends 'crud/base.html' %}

{% load widget_tweaks %}

{% block content %}
<div class="container" style="padding:40px;">
	<div class="row">
		<div class="col-10">
			<h6 style="text-align:center;"><font color="red"> All fields are required</font> </h6>
		</div>
		<div class="col-10">
			<form method="post" novalidate>
				{% csrf_token %}
				{% for hidden_field in form.hidden_fields %}
					   {{ hidden_field }}
					 {% endfor %}
				{% for field in form.visible_fields %}
				<div class="form-group">
				 {{ field.label_tag }}
				 {% render_field field class="form-control" %}
				 {% if field.help_text %}
					<small class="form-text text-muted">{{ field.help_text }}</small>
				 {% endif %}
				</div>
				{% endfor %}
			<button type="submit" class="btn btn-primary">Add New Post</button>
		    </form>
		</div>
	</div>
</div>
{% endblock %}
myapp/templates/crud/post-detail.html
 
//myapp/templates/crud/post-detail.html
{% extends 'crud/base.html' %}

{% block content %}
<div class="container" style="padding:40px;">
	<div class="row">
		<div class="col-8">
			<p class="h2">{{post.title}}</p>
		</div>
		<div class="col-4">
		  	<a href="/"><button type="button" class="btn btn-info">Back</button></a> |
		  	<a href="{% url 'edit' post.pk %}"><button type="button" class="btn btn-info">Edit</button></a> |
			<a href="{% url 'delete' post.pk %}"><button type="button" class="btn btn-danger">Delete</button></a>
		</div>
	</div>
	<div class="row">
		<div class="col-12">
			{{post.message}}
		</div>
	</div>
</div>
{% endblock %}
myapp/templates/crud/edit.html
 
//myapp/templates/crud/edit.html
{% extends 'crud/base.html' %}

{% load widget_tweaks %}

{% block content %}
<div class="container" style="padding:40px;">
	<div class="row">
		<div class="col-10">
			<h6 style="text-align:center;"><font color="red"> All fields are required</font> </h6>
		</div>
		<div class="col-10">
	   <form method="post" novalidate>
			{% csrf_token %}
			{% for hidden_field in form.hidden_fields %}
				   {{ hidden_field }}
				 {% endfor %}
			{% for field in form.visible_fields %}
				   <div class="form-group">
					 {{ field.label_tag }}
					 {% render_field field class="form-control" %}
					 {% if field.help_text %}
					   <small class="form-text text-muted">{{ field.help_text }}</small>
					 {% endif %}
				   </div>
				 {% endfor %}
			<button type="submit" class="btn btn-primary">Update Post</button>
		</form>
		</div>
	</div>
</div>
{% endblock %}
myapp/templates/crud/confirm_delete.html
 
//myapp/templates/crud/confirm_delete.html
{% extends 'crud/base.html' %}
{% block content %}
<div class="container" style="padding:20px;">
	<div class="row">
		<div class="col-md-10 col-xs-10 col-sm-10">
			<form method="post">
				{% csrf_token %}
				<div class="form-row">
				  <div class="alert alert-warning">
				   Are you sure you want to delete {{ object }}?
				  </div>
				</div>
				<button type="submit" class="btn btn-danger">Delete</button>
			</form>
		</div>
	</div>
</div>
{% endblock %}
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',
    'widget_tweaks', 
]
registered post in admin
and login to admin http://127.0.0.1:8000/admin
 
//myapp/admin.py
from django.contrib import admin
from .models import Post #add this to import the Post model

# Register your models here.
admin.site.register(Post) #add this to register the Post model
Run : C:\my_project_django\testdev>python manage.py runserver

Python Django Upload Multiple Files using jQuery AJAX

Python Django Upload Multiple Files 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('admin/', admin.site.urls),
    path('', views.upload_files, name='upload_files'),
	path('upload', views.upload_files, name='upload_files'),
]
myapp/views.py
 
//myapp/views.py
from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import ensure_csrf_cookie

@ensure_csrf_cookie
def upload_files(request):
    if request.method == "GET":
        return render(request, 'index.html', )
    if request.method == 'POST':
        files = request.FILES.getlist('files[]', None)
        #print(files)
        for f in files:
            handle_uploaded_file(f)
        return JsonResponse({'msg':'<div class="alert alert-success" role="alert">File successfully uploaded</div>'})
    else:
        return render(request, 'index.html', )
			
def handle_uploaded_file(f):  
    with open('myapp/static/upload/'+f.name, 'wb+') as destination:  
        for chunk in f.chunks():  
            destination.write(chunk) 
myapp/templates/index.html
 
//myapp/templates/index.html
{% extends 'base.html' %}

{% block body %}
	<div style="width: 500px; margin: auto;">
		<fieldset name="Multiple Files Upload">
			{% if msg %} {% autoescape off %} {{ msg }} {% endautoescape %} {% endif %}
			<div id="msg"></div>
			<p>
				{% csrf_token %}
				<input type="file" id="multiFiles" name="files[]" multiple="multiple"/>
				<button id="upload" class="btn btn-primary">Upload</button>
			</p>
		</fieldset>
	</div>
{% endblock %}
myapp/templates/base.html
 
//myapp/templates/base.html
<!DOCTYPE html>
<html>
<head>
<title>Python Django Upload Multiple Files using jQuery AJAX - cairocoders</title>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"/>
</head>
<body>
<div class="container">
    <div class="row">
        <p><h3 class="text-primary">Python Django Upload Multiple Files using jQuery AJAX</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 type="text/javascript">
$(document).ready(function (e) {
	$('#upload').on('click', function () {
		var form_data = new FormData();
		var ins = document.getElementById('multiFiles').files.length;
					
		if(ins == 0) {
			$('#msg').html('<div class="alert alert-danger" role="alert">Select at least one file</div>');
			return;
		}
					
		for (var x = 0; x < ins; x++) {
			form_data.append("files[]", document.getElementById('multiFiles').files[x]);
		}
					
		csrf_token = $('input[name="csrfmiddlewaretoken"]').val();
					
		//console.log(csrf_token);
					
		form_data.append("csrfmiddlewaretoken", csrf_token);
					
		$.ajax({
			url: 'upload', // point to server-side URL
			dataType: 'json', // what to expect back from server
			cache: false,
			contentType: false,
			processData: false,
			//data: {'data': form_data, 'csrfmiddlewaretoken': csrf_token},
			data: form_data,
			type: 'post',
			success: function (response) { // display success response
				$('#msg').html(response.msg);
			},
			error: function (response) {
				$('#msg').html(response.message); // display error 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',
]
Run : C:\my_project_django\testdev>python manage.py runserver

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

Sunday, April 3, 2022

Python Django How To Use DataTables with Insert Data Jquery Ajax

Python Django How To Use DataTables with Insert Data 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

https://datatables.net/
DataTables is a powerful jQuery plugin for creating table listings and adding interactions to them. It provides searching, sorting and pagination without any configuration. 


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):
    all_members = Member.objects.all()
    return render(request, 'datatables/index.html', {'all_members': all_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/datatables/index.html
 
//myapp/templates/datatables/index.html
{% extends 'datatables/base.html' %}
{% block body %}
<p>
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addnewmember" style="width:300px;">
  Add New
</button>
</p>
<!-- Modal -->
<div class="modal fade" id="addnewmember" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Add New</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-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>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" id="submit">Submit</button>
      </div>
	  </form>
    </div>
  </div>
</div>

<hr style="border-top:1px solid #000; clear:both;"/>
<table id = "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 all_members %}
        <tr>
            <td>{{ member.firstname }}</td>
            <td>{{ member.lastname }}</td>
            <td>{{ member.address  }}</td>
        </tr>
        {% endfor %}
    </tbody>
</table>
{% endblock %}
myapp/templates/datatables/base.html
 
//myapp/templates/datatables/base.html
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Python Django How To Use DataTables with Insert Data Jquery Ajax</title>
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"/>
	<link rel = "stylesheet" type = "text/css" href = "https://cdn.datatables.net/1.11.5/css/jquery.dataTables.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 How To Use DataTables with Insert Data 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="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
<script src = "https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script type = "text/javascript">
$(document).ready(function(){
    $('#table').DataTable();
	
    $('#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 = "/";
                }
            });
        }
    });
});
</script>
</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

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