简体   繁体   English

显示从django数据库到fullcalendar的事件

[英]display events from django database to fullcalendar

I am on a django project in which I want to display events from the django database to fullcalendar.我在一个 django 项目中,我想在其中显示从 django 数据库到 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).我遇到的问题类似于这个FullCalendar 不显示事件,但我没有使用 php 并且我无法想象我遗漏了什么(我猜这是 Ajax 给出答案的请求)。 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.我不想将事件从 JS 添加到数据库,只是通过从数据库中检索它们来显示它们。 Additions to the database will be done later with django and python via a form.稍后将通过表格使用 django 和 python 向数据库添加内容。 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:我的模板 html 和 Fullcalendar:

{% extends 'base_admin.html' %}
{% load static %}
{% block head_shedule_content %}
{% load static %}
<link href='https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/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 class="page-section portfolio" id="planning">
        <div class="container">
            <!-- Portfolio Section Heading-->
            <h2 class="page-section-heading text-center text-uppercase text-secondary mb-0">Planning</h2>
            <!-- Icon Divider-->
            <div class="divider-custom">
                <div class="divider-custom-line"></div>
                <div class="divider-custom-icon"><i class="fa-solid fa-bone"></i></div>
                <div class="divider-custom-line"></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.这是我评论的返回内容,它对应于我在上下文中发送的 datatest 变量。 screen of the return退货画面

I hope I have given enough detail without drowning you in the reading.我希望我已经提供了足够的细节而不会让你淹没在阅读中。 Regards问候

It looks like datatest is already a JSON string when you put it inside the appointment property.当您将 datatest 放入appointment属性时,它看起来已经是一个datatest字符串。 So you can't loop through appointment the way you're trying to because it's a piece of text, not an array.所以你不能按照你尝试的方式循环appointment ,因为它是一段文本,而不是数组。

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.同样在数据测试中,您可以清楚地看到数据没有“原因”、“开始日期”或“结束日期”属性……您已经将它们转换为datatest期望的名称。

Therefore I think in the fullCalendar JS code you should just be able to write:因此我认为在 fullCalendar JS 代码中你应该可以这样写:

events: {{ appointment }}

to inject the JSON directly into the JS code (and have it treated as an array literal).将 JSON 直接注入 JS 代码(并将其视为数组文字)。

document.addEventListener('DOMContentLoaded', function() {
    var calendarEl = document.getElementById('calendar');
    var calendar = new FullCalendar.Calendar(calendarEl, {


        editable:true,
        selectable:true,
        contentWidth:300,
        navLinks: true,

       events: {{ appointment|safe }},
});

         calendar.render();
});

I fixed it like this and solved it well Thank you.我这样修好了,很好解决了 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM