Django Fullcalendar Ajax Example Tutorial

Published On: 07/09/2022 | Category: Django


Hi Dev,

This tutorial will provide example of django fullcalendar ajax example tutorial. I would like to share with you django fullcalendar example. this example will help you django fullcalendar crud example. you will learn django fullcalendar ajax.

In this example, we will simply create a crud application with full calendar so you can easily create events, edit events by drag and drop and delete event. in this example, we will create an events table with a start, edit date, and title column. then you can add, edit and delete that event with the database.

Here i explained simply step by step example of django fullcalendar ajax example tutorial.

You can see bellow preview of ajax crud app.

Preview:

Step 1: Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2: Create a App

Now we'll create a single app called core to store a list of post names. We're keeping things intentionally basic. Stop the local server with Control+c and use the startapp command to create this new app.

python3 manage.py startapp core
Step 3: Update setting.py

Then update INSTALLED_APPS within our settings.py file to notify Django about the app.

settings.py

....
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'core',
]
Step 4: Create a Model

Now go for the models we will We'll call our single model Post and it will have just two fields: title and description. And finally set __str__ to display the name of the post in admin interface.

core/models.py
from django.db import models

# Create your models here.
class Event(models.Model):
    title = models.CharField(max_length=255)
    start = models.DateField()
    end = models.DateField()

    def __str__(self):
        return self.title

Ok, all set. We can engender a migrations file for this change, then integrate it to our database via migrate.

python manage.py makemigrations
python manage.py migrate
Step 5: Creating the Views

In this step, we need to configure our five views. The calendar page will just be a template. all_events view is fetch the all data between two start date and end date into database, add_event View is create a event in our calendar,update function is basically update your event to drag and drop event as well as dateremove when click the created event button open the popup and delete the event open the core/views.py file and add:

core/views.py
from django.shortcuts import render
from .models import Event
from django.core import serializers
from django.http import HttpResponse, JsonResponse
import json
from django.urls import reverse

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

# Display all events.
def all_events(request):                                                                                                 
    all_events = Event.objects.all()                                                                                    
    out = []                                                                                                             
    for event in all_events:                                                                                             
        out.append({                                                                                                     
            'title': event.title,                                                                                         
            '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)  

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

# Update event.
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 = Event.objects.get(id=id)
    event.start = start
    event.end = end
    event.title = title
    event.save()
    data = {}
    return JsonResponse(data)

# Remove event.
def remove(request):
    id = request.GET.get("id", None)
    event = Event.objects.get(id=id)
    event.delete()
    data = {}
    return JsonResponse(data)
Step 6: Creating the Templates

Next, then with your text editor create new templates files: core/templates/calendar.html file and the add:

core/templates/calendar.html
<html>
<head>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.css"/>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.css"/>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" />
    <style type="text/css">
        .fc-title{
            color: white !important;
        }
    </style>
    <script>

        /*------------------------------------------
        --------------------------------------------
        Calendar 
        --------------------------------------------
        --------------------------------------------*/
        $(document).ready(function () {
            var calendar = $('#calendar').fullCalendar({
                header: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'month,agendaWeek,agendaDay'
                },
                displayEventTime: false,
                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");
                        var end = $.fullCalendar.formatDate(end, "Y-MM-DD");
                        $.ajax({
                            type: "GET",
                            url: '/add_event',
                            data: {'title': title, 'start': start, 'end': end},
                            dataType: "json",
                            success: function (data) {
                                calendar.fullCalendar('refetchEvents');
                                displayMessage("Event Created Successfully");
                            },
                            error: function (data) {
                                alert('There is a problem!!!');
                            }
                        });
                    }
                },
                eventResize: function (event) {
                    var start = $.fullCalendar.formatDate(event.start, "Y-MM-DD");
                    var end = $.fullCalendar.formatDate(event.end, "Y-MM-DD");
                    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');
                            displayMessage("Event Updated Successfully");
                        },
                        error: function (data) {
                            alert('There is a problem!!!');
                        }
                    });
                },
                eventDrop: function (event) {
                    var start = $.fullCalendar.formatDate(event.start, "Y-MM-DD");
                    var end = $.fullCalendar.formatDate(event.end, "Y-MM-DD");
                    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');
                            displayMessage("Event Updated Successfully");
                        },
                        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');
                                displayMessage("Event Delete Successfully");
                            },
                            error: function (data) {
                                alert('There is a problem!!!');
                            }
                        });
                    }
                },
            });
        });
    
    /*------------------------------------------
    --------------------------------------------
    Toastr Success Code
    --------------------------------------------
    --------------------------------------------*/
    function displayMessage(message) {
        toastr.success(message, 'Event');
    } 

    </script>
</head>
<body>
<br/>
<h2 align="center"><a href="#">Django Fullcalendar Ajax Example Tutorial - Tuts-Station.com</a></h2>
<br/>
<div class="container">
    <div id="calendar"></div>
</div>
</body>
</html>
Step 7: Creating URLs

In this section, we need a urls.py file within the core app however Django doesn't create one for us with the startapp command. Create core/urls.py with your text editor and paste below code.

core/urls.py
from django.urls import re_path
from .views import calendar, add_event, update, remove, all_events

urlpatterns = [
    re_path('^calendar', calendar, name='calendar'),
    re_path('^add_event$', add_event, name='add_event'),
    re_path('^update$', update, name='update'),
    re_path('^remove', remove, name='remove'),
    re_path('^all_events', all_events, name='all_events')
]

Next, we require to add a URL path for our example app which can be done by importing include and setting a path for it.

example/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('core.urls')),
]
Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python manage.py runserver

Next, go to the http://localhost:8000/calendar address with a web browser.

I hope it will help you....

Happy Coding!