article

Saturday, May 21, 2022

Python Django Ajax FullCalender CRUD (Create, Read, Update and Delete) Mysql Database

Python Django Ajax FullCalender CRUD (Create, Read, Update and Delete) Mysql Database

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 Events(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255,null=True,blank=True)
    start = models.DateTimeField(null=True,blank=True)
    end = models.DateTimeField(null=True,blank=True)

    class Meta:  
        db_table = "tblevents"
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
from django.http import JsonResponse 
from myapp.models import Events 

# Create your views here.
def index(request):  
    all_events = Events.objects.all()
    context = {
        "events":all_events,
    }
    return render(request,'index.html',context)

def all_events(request):                                                                                                 
    all_events = Events.objects.all()                                                                                    
    out = []                                                                                                             
    for event in all_events:                                                                                             
        out.append({                                                                                                     
            'title': event.name,                                                                                         
            'id': event.id,                                                                                              
            'start': event.start.strftime("%m/%d/%Y, %H:%M:%S"),                                                         
            'end': event.end.strftime("%m/%d/%Y, %H:%M:%S"),                                                             
        })                                                                                                               
                                                                                                                     
    return JsonResponse(out, safe=False) 

def add_event(request):
    start = request.GET.get("start", None)
    end = request.GET.get("end", None)
    title = request.GET.get("title", None)
    event = Events(name=str(title), start=start, end=end)
    event.save()
    data = {}
    return JsonResponse(data)

def update(request):
    start = request.GET.get("start", None)
    end = request.GET.get("end", None)
    title = request.GET.get("title", None)
    id = request.GET.get("id", None)
    event = Events.objects.get(id=id)
    event.start = start
    event.end = end
    event.name = title
    event.save()
    data = {}
    return JsonResponse(data)

def remove(request):
    id = request.GET.get("id", None)
    event = Events.objects.get(id=id)
    event.delete()
    data = {}
    return JsonResponse(data)
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://fullcalendar.io/
CND : https://cdnjs.com/libraries/fullcalendar/3.9.0

/myapp/templates/index.html
 
//myapp/templates/index.html
{% extends "base.html" %}
  
{% block title %}Python Django Ajax FullCalender CRUD (Create, Read, Update and Delete){% endblock title %}
  
{% block content %}
<div class="col-md-12">    
    <div id='calendar'></div> 
</div> 
{% endblock content %} 
myapp/templates/base.html
//myapp/templates/base.html
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 9 Ajax FullCalender CRUD (Create, Read, Update and Delete)</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
     
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.9.0/fullcalendar.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.9.0/fullcalendar.js"></script>
</head>
<body>
<div class="container">
 <div class="row">
    <h4>Python Django Ajax FullCalender CRUD (Create, Read, Update and Delete)</h4> 
    {% block content %}{% endblock %}
 </div>
</div>
<script>
   $(document).ready(function () {
       var calendar = $('#calendar').fullCalendar({
           header: {
               left: 'prev,next today',
               center: 'title',
               right: 'month,agendaWeek,agendaDay'
           },
           events: '/all_events',
           selectable: true,
           selectHelper: true,
           editable: true,
           eventLimit: true,
           select: function (start, end, allDay) {
               var title = prompt("Enter Event Title");
               if (title) {
                   var start = $.fullCalendar.formatDate(start, "Y-MM-DD HH:mm:ss");
                   var end = $.fullCalendar.formatDate(end, "Y-MM-DD HH:mm:ss");
                   $.ajax({
                       type: "GET",
                       url: '/add_event',
                       data: {'title': title, 'start': start, 'end': end},
                       dataType: "json",
                       success: function (data) {
                           calendar.fullCalendar('refetchEvents');
                           alert("Added Successfully");
                       },
                       error: function (data) {
                           alert('There is a problem!!!');
                       }
                   });
               }
           },
           eventResize: function (event) {
               var start = $.fullCalendar.formatDate(event.start, "Y-MM-DD HH:mm:ss");
               var end = $.fullCalendar.formatDate(event.end, "Y-MM-DD HH:mm:ss");
               var title = event.title;
               var id = event.id;
               $.ajax({
                   type: "GET",
                   url: '/update',
                   data: {'title': title, 'start': start, 'end': end, 'id': id},
                   dataType: "json",
                   success: function (data) {
                       calendar.fullCalendar('refetchEvents');
                       alert('Event Update');
                   },
                   error: function (data) {
                       alert('There is a problem!!!');
                   }
               });
           },

           eventDrop: function (event) {
               var start = $.fullCalendar.formatDate(event.start, "Y-MM-DD HH:mm:ss");
               var end = $.fullCalendar.formatDate(event.end, "Y-MM-DD HH:mm:ss");
               var title = event.title;
               var id = event.id;
               $.ajax({
                   type: "GET",
                   url: '/update',
                   data: {'title': title, 'start': start, 'end': end, 'id': id},
                   dataType: "json",
                   success: function (data) {
                       calendar.fullCalendar('refetchEvents');
                       alert('Event Update');
                   },
                   error: function (data) {
                       alert('There is a problem!!!');
                   }
               });
           },

           eventClick: function (event) {
               if (confirm("Are you sure you want to remove it?")) {
                   var id = event.id;
                   $.ajax({
                       type: "GET",
                       url: '/remove',
                       data: {'id': id},
                       dataType: "json",
                       success: function (data) {
                           calendar.fullCalendar('refetchEvents');
                           alert('Event Removed');
                       },
                       error: function (data) {
                           alert('There is a problem!!!');
                       }
                   });
               }
           },

       });
   });

</script>
</body>
</html>
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('all_events/', views.all_events, name='all_events'), 
    path('add_event/', views.add_event, name='add_event'), 
    path('update/', views.update, name='update'),
    path('remove/', views.remove, name='remove'),
]
Run : C:\django\devproject>python manage.py runserver

Related Post