Home > front end >  display events from django database to fullcalendar
display events from django database to fullcalendar

Time:05-04

I am on a django project in which I want to display events from the django database to fullcalendar.

The problem I'm having is similar to this one FullCalendar not displaying events but I'm not using php and I'm having trouble visualizing what I'm missing (I guess it's the Ajax request given the answer provided). Currently it is as if my context was not processed.

I don't want to add events from JS to the database, just display them by retrieving them from the database. Additions to the database will be done later with django and python via a form. Thanking you in advance for your clarifications.

My calendar view code:

class ScheduleCalendarView(LoginRequiredMixin, View):
def get(self, request):
    all_events = Planning.objects.all()
    event_arr = []
    for i in all_events:
        event_sub_arr = {}
        event_sub_arr['title'] = i.reason
        start_date = datetime.strptime(str(i.appointment_date_start.date()), "%Y-%m-%d").strftime("%Y-%m-%d")
        end_date = datetime.strptime(str(i.appointment_hour_stop.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)
    data = JsonResponse((event_arr), safe=False)
    datatest = json.dumps(event_arr)
        #return HttpResponse(json.dumps(event_arr))
    print(data, type(data))
    print(datatest, type(datatest))
    #return HttpResponse(json.dumps(event_arr))
    context = {
        "appointment": datatest
    }

    return render(request, "schedule/fullcalendar.html", context)

My template html with Fullcalendar:

{% extends 'base_admin.html' %}
{% load static %}
{% block head_shedule_content %}
{% load static %}
<link href='https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css' rel='stylesheet'>
<link href="{% static 'css/fullcalendar/main.css' %}" rel='stylesheet' />
<script src="{% static 'js/fullcalendar/main.js' %}"></script>
<script src="{% static 'js/fullcalendar/locales-all.js' %}"></script>
<script>

  document.addEventListener('DOMContentLoaded', function() {
    var initialLocaleCode = 'fr';
    var calendarEl = document.getElementById('calendar');
    var calendar = new FullCalendar.Calendar(calendarEl, {
      themeSystem: 'bootstrap5',
      headerToolbar: {
        left: 'prev,next today',
        center: 'title',
        right: 'dayGridMonth,timeGridWeek,timeGridDay,listMonth'
      },
      locale: initialLocaleCode,
      navLinks: true, // can click day/week names to navigate views
      businessHours: true, // display business hours
      editable: true,
      selectable: true,
      weekNumbers: true,
      dayMaxEvents: true, // allow "more" link when too many events
      events: [
        {% for i in appointment %}
            {
                title: "{{ i.reason }}",
                start: '{{ i.start_date|date:"Y-m-d" }}',
                end: '{{ i.end_date|date:"Y-m-d" }}',
            },
        {% endfor %}
        {
      title: 'Click for Google',
      url: 'http://google.com/',
      start: '2022-04-28'
    }
      ]
    });
    calendar.render();
  });
</script>
<style>



#top {
background: #eee;
border-bottom: 1px solid #ddd;
padding: 0 10px;
line-height: 40px;
font-size: 12px;
}

#calendar {
max-width: 1100px;
margin: 40px auto;
padding: 0 10px;
}

</style>
{% endblock %}
{% block content %}
{% load static %}
    <!-- Portfolio Section-->
    <section  id="planning">
        <div >
            <!-- Portfolio Section Heading-->
            <h2 >Planning</h2>
            <!-- Icon Divider-->
            <div >
                <div ></div>
                <div ><i ></i></div>
                <div ></div>
            </div>
        <div id='calendar'></div>
        </div>
    </section>
{% endblock %}

There is an event out of the loop for testing display. Displaying the hard-coded event, out-of-loop event works well. screen of my calendar

Here is the content of my commented return which corresponds to my datatest variable that I send in the context. screen of the return

I hope I have given enough detail without drowning you in the reading. Regards

CodePudding user response:

It looks like datatest is already a JSON string when you put it inside the appointment property. So you can't loop through appointment the way you're trying to because it's a piece of text, not an array.

Also in datatest you can clearly see that the data doesn't have the "reason", "start_date" or "end_date" properties...you've already converted them to the names fullCalendar expects.

Therefore I think in the fullCalendar JS code you should just be able to write:

events: {{ appointment }}

to inject the JSON directly into the JS code (and have it treated as an array literal).

  • Related