显示从Django数据库到FullCalendar的事件

发布于 2025-01-25 17:46:30 字数 4462 浏览 2 评论 0原文

我正在一个Django项目中,我想在其中显示从Django数据库到FullCalendar的事件。

我遇到的问题与此相似 fullcalendar不显示事件,但我不是使用PHP,我很难可视化我所缺少的内容(我想这是给定答案的Ajax请求)。目前,好像我的上下文没有处理过。

我不想将事件从JS添加到数据库,只需通过从数据库中检索它们来显示它们。数据库的添加将在稍后通过Django和Python通过表单完成。 事先感谢您的澄清。

我的日历视图代码:

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)

带有FullCalendar的模板HTML:

{% 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 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 %}

有一个事件以进行测试显示。展示硬编码的事件,越野事件效果很好。 我的日历的屏幕

这是我注释的返回的内容,它与我的datateTest变量相对应,我在上下文中发送。 返回的屏幕

我希望我希望我能提供足够的细节,而不会在阅读中淹死您。 问候

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 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.
screen of the return

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

绝影如岚 2025-02-01 17:46:30

当您将其放入“约会”属性中时,看起来DataTest已经是JSON字符串。因此,您不能以约会循环您试图使用的方式,因为它是文本,而不是数组。

另外,在datatest中,您可以清楚地看到数据没有“原因”,“ start_date”或“ end_date”属性...您已经将它们转换为FullCalendar期望的名称。

因此,我认为在FullCalendar JS代码中,您应该可以写入:

events: {{ appointment }}

将JSON直接注入JS代码(并将其视为数组文字)。

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).

美男兮 2025-02-01 17:46:30
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();
});

我这样修复了它,并很好地解决了它,谢谢。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文