So, I have an appointment models
class Appointment(models.Model):
user = models.ForeignKey(User)
date = models.DateField()
time = models.TimeField()
doctorName = models.CharField(max_length=50)`
And I want to implement this in the FullCalendar
tool. I'm not sure how to even begin. Any help is appreciated. Thanks.
What is Fullcalendar? FullCalendar is a JavaScript library that seamlessly integrates with such popular JavaScript frameworks as Vue, React, Angular. Thanks to its excellent documentation, one won't have trouble incorporating the library into projects.
FullCalendar provides settings, methods, and callbacks for interacting with and switching the current view. The initial view when the calendar loads. A View object contains information about a calendar view, such as title and date range.
Since your question shows you haven't tried anything , guessing you know javascript and tried some hands on full calendar js.
Suppose you have model named Event for displaying different events in calendar.
class Events(models.Model):
even_id = models.AutoField(primary_key=True)
event_name = models.CharField(max_length=255,null=True,blank=True)
start_date = models.DateTimeField(null=True,blank=True)
end_date = models.DateTimeField(null=True,blank=True)
event_type = models.CharField(max_length=10,null=True,blank=True)
def __str__(self):
return self.event_name
In your views.py
def event(request):
all_events = Events.objects.all()
get_event_types = Events.objects.only('event_type')
# if filters applied then get parameter and filter based on condition else return object
if request.GET:
event_arr = []
if request.GET.get('event_type') == "all":
all_events = Events.objects.all()
else:
all_events = Events.objects.filter(event_type__icontains=request.GET.get('event_type'))
for i in all_events:
event_sub_arr = {}
event_sub_arr['title'] = i.event_name
start_date = datetime.datetime.strptime(str(i.start_date.date()), "%Y-%m-%d").strftime("%Y-%m-%d")
end_date = datetime.datetime.strptime(str(i.end_date.date()), "%Y-%m-%d").strftime("%Y-%m-%d")
event_sub_arr['start'] = start_date
event_sub_arr['end'] = end_date
event_arr.append(event_sub_arr)
return HttpResponse(json.dumps(event_arr))
context = {
"events":all_events,
"get_event_types":get_event_types,
}
return render(request,'admin/poll/event_management.html',context)
And finally in your template setup full calendar with including necessary CSS,JS Files and HTML code.And then ,
<script>
$(document).ready(function() {
$('#calendar').fullCalendar({
defaultDate: '2016-07-19',
editable: true,
eventLimit: true, // allow "more" link when too many events
events: [
{% for i in events %}
{
title: "{{ i.event_name}}",
start: '{{ i.start_date|date:"Y-m-d" }}',
end: '{{ i.end_date|date:"Y-m-d" }}',
},
{% endfor %}
]
});
});
</script>
Dynamically on some event you need to change events for example by changing dropdown you need to filter events ,
$(document).ready(function(){
$('.event_types').on('change',function(){
var event_type = $.trim($(this).val());
$.ajax({
url: "{% url 'manage-event' %}",
type: 'GET',
data:{"event_type":event_type},
cache: false,
success: function (response) {
var event_arr = $.parseJSON(response);
$('#calendar').fullCalendar('removeEvents');
$('#calendar').fullCalendar('addEventSource', event_arr);
$('#calendar').fullCalendar('rerenderEvents' );
},
error: function () {
alert("error");
}
})
})
})
You can use following code to add, remove, update event in full calendar:
model:
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)
def __str__(self):
return self.name
view:
def calendar(request):
all_events = Events.objects.all()
context = {
"events":all_events,
}
return render(request,'calendar.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)
urls:
from .views import calendar, add_event, update, remove, all_events
url('^calendar', calendar, name='calendar'),
url('^add_event$', add_event, name='add_event'),
url('^update$', update, name='update'),
url('^remove', remove, name='remove'),
url('^all_events', all_events, name='all_events')
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>
$(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>
</head>
<body>
<br/>
<h2 align="center"><a href="#">title</a></h2>
<br/>
<div class="container">
<div id="calendar"></div>
</div>
</body>
</html>
Example:To add event to fullcalendar you should add event to your model or if you don't want to save them you should create event and send to fullcalendar(in def calendar). For example to add event to all Sundays of 2020:
view:
def calendar(request):
from datetime import date, timedelta
d = date(2020, 1, 1)
d += timedelta(days=6 - d.weekday()) # First Sunday
all_sunday_in_2020 = []
while d.year != 2021:
all_sunday_in_2020.append({'name': 'my-title', 'start': d, 'end': d
+ timedelta(days=1)})
d += timedelta(days=7)
return render(request,'calendar.html',{'events':all_sunday_in_2020})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With