在Django中使用fullCalendar [英] Using fullCalendar in Django

查看:520
本文介绍了在Django中使用fullCalendar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里发布的问题的一些后续行动( Django:通过自定义模板标签修改数据与用户输入),但是由于提出了这个问题,我决定采取不同的方法。您可以告诉我是一个新手,所以请轻松一点。

Somewhat of a follow-up to the question posted here (Django: modifying data with user input through custom template tag?), but since asking the question I've decided to take a different approach. As you can tell I'm a newb so please go easy.

我想在我的Django应用程序中显示每周日历,显示数据库中的变化。以下是Shift模型。

I want a weekly calendar in my Django app that displays shifts in the database. Following is the Shift model.

class Shift(models.Model):
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='shifts',
        blank=True, null=True) # A shift may not have an owner.

    # Choices for fields. Add more choices as necessary.
    DAYS = (
        ('M', 'Monday'),
        ('TU', 'Tuesday'),
        ('W', 'Wednesday'),
        ('TH', 'Thursday'),
        ('F', 'Friday'),
        ('SA', 'Saturday'),
        ('SU', 'Sunday'),
    )

    day_of_the_week = models.CharField(max_length=2, choices=DAYS, blank=True, null=True)
    start_date = models.DateField(blank=True, null=True)
    end_date = models.DateField(blank=True, null=True)
    start_time = models.TimeField(default='12:00:00')
    end_time = models.TimeField(default='14:00:00')
    hours = models.DurationField(editable=False)
    activated = models.BooleanField(verbose_name='Activate', default=False)
    sale_status = models.BooleanField(verbose_name='Activate sale', default=False)

    ...

    def save(self, *args, **kwargs): # Overwrite save() to calculate and save the duration of a shift.
        temp_date = datetime(1,1,1,0,0,0)
        self.hours = datetime.combine(temp_date, self.end_time) - datetime.combine(temp_date, self.start_time)
        super(Shift, self).save(*args, **kwargs)

管理员创造转变,并让所有者转移。一旦所有者被分配,所有者可以出售转移,这将改变 sale_status = False sale_status = True 。然后其他用户可以购买转账,更改向买方转移的所有者,并将转账的 sale_status 更改为。理想情况下,这些行为(销售和购买转变)可以通过日历进行,通过点击转移。这意味着日历必须显示 activated = True 的所有班次。

An admin creates shifts and assigns owners to the shifts. Once an owner is assigned, the owner can sell the shift, which will change sale_status=False to sale_status=True. Then other users can buy the shift, changing the owner of the shift to the buyer and the shift's sale_status to False. Ideally, these actions (selling and buying shifts) can be performed through the calendar, by clicking on a shift. That means the calendar has to display all the shifts whose activated=True.

我一直在挖掘现在一段时间,决定使用 FullCalendar 。展望未来,我知道我必须为AJAX视图修改我的 views.py ,并为日历创建一个模板,但我不知道如何做。我的模板目前看起来像这样:

I've been digging into this for a while now and decided to use FullCalendar. Going forward, I know I have to modify my views.py for an AJAX view and create a template for the calendar, but I am not sure how to do either. My template currently looks like this:

<head>
<link rel='stylesheet' href='fullcalendar/fullcalendar.css' />
<script src='lib/jquery.min.js'></script>
<script src='lib/moment.min.js'></script>
<script src='fullcalendar/fullcalendar.js'></script>
</head>

<div id="calendar"></div>
<script type='text/javascript'>
$(document).ready(function() {

    // page is now ready, initialize the calendar...

    $('#calendar').fullCalendar({
        // put your options and callbacks here
        events: "shifts/eventsFeed",
        weekends: false,
        editable: false,
    })

});
</script>

这显然是错误的(不使用Django的模板语言,eventsFeed未实现等)我不知道如何从这里走。

This is obviously wrong (does not use Django's template language, eventsFeed is not implemented, etc.) but I'm not sure how to go from here.

任何帮助,特别是代码片段,将不胜感激。

Any help, especially with snippets of code, will be greatly appreciated.

谢谢!

修改:所以我可以使用以下代码加载日历:

Edit: So I was able to get the calendar to load with following codes:

// in views.py
def view_shifts(request):
    """
    View for displaying activated shifts in a weekly calendar format.
    """

    activated_shifts = Shift.objects.filter(activated=True) # Get all the activated shifts.
    shifts = [] # place holder
    for shift in activated_shifts:
        temp = OrderedDict()
        temp['id'] = shift.id
        temp['title'] = shift.title
        temp['start'] = str(shift.start_date) + 'T' + str(shift.start_time)
        temp['end'] = str(shift.end_date) + 'T' + str(shift.end_time)
        shifts.append(temp)

    calendar_config_options = {'header': {
                                    'left': 'prev,next today',
                                    'center': 'title',
                                    'right': 'month,agendaWeek,agendaDay'
                                },
                               'defaultView': 'agendaWeek',
                               'editable': 'True', # View only.
                               'events': json.dumps(shifts),
                               'firstDay': 1 # Week starts on Monday.
                               }

    return render(request, 'shifts/full_calendar.html', {'calendar_config_options': calendar_config_options})

我还将字段标题添加到我的 Shift 中。它只是 self.owner 的字符串表示形式。
我的模板称为 calendar_init.html ,如下所示:

I also added the field title to my Shift. It is simply the string representation of self.owner. My template, called calendar_init.html, is as following:

<script type="text/javascript">
    $(document).ready(function() { // Page is ready.
        // Initialize the calendar.
        $('#calendar').fullCalendar({{ calendar_config_options }});
    });
</script>

现在,当渲染模板时,我得到以下内容:

Now, when the template is rendered, I get the following:

<!DOCTYPE html>
<head>

    <title>Shifts</title>

    ...

    <script type="text/javascript">
    $(document).ready(function() { // Page is ready.
        // Initialize the calendar.
        $('#calendar').fullCalendar({'firstDay': 1, 'header': {'right': 'month,agendaWeek,agendaDay', 'center': 'title', 'left': 'prev,next today'}, 'defaultView': 'agendaWeek', 'editable': True, 'events': '[{"id": 61, "title": "Unclaimed", "start": "2015-07-21T14:00:00", "end": "2015-07-21T16:00:00"}, {"id": 62, "title": "slee17", "start": "2015-07-21T12:00:00", "end": "2015-07-21T14:00:00"}]'});
    });
</script>

</head>

<body>
<div id="calendar"></div>

然而,日历仍然是没有加载班我试过使用 json.loads(json.dumps(shift))而不是 json.dumps(shift)并尝试使用 http:/ /robotfantastic.org/serializing-python-data-to-json-some-edge-cases.html 。也没有加载日历与班次。我在这里做错了什么? (日历仍在加载,其配置是按照我的配置,但日历是空的。)

However, the calendar is still not loaded with shifts. I've tried using json.loads(json.dumps(shifts)) instead of json.dumps(shifts) and have also tried using the helper functions from http://robotfantastic.org/serializing-python-data-to-json-some-edge-cases.html. Neither have loaded the calendar with shifts. What am I doing wrong here? (The calendar is still being loaded, its configuration is as I have configured, but the calendar is empty.)

另外两个小问题:
1)当我说'edtiable':True 而不是'editable':'True',该页面变为空白,没有错误。为什么这样呢我也尝试过'weekends'='False',这仍然显示了周末的日历,所以日历显然没有被配置正确的,当涉及到布尔。我不知道为什么,因为其他配置设置(例如 defaultView firstDay )似乎都没事了。
2)我使用了OrderedDict(),因为我怀疑在尝试将事件加载到日历时很重要,但我不知道这个是真的。我可以使用普通的Python字典吗?

Also, two small questions: 1) when I say 'edtiable': True instead of 'editable': 'True', the page goes blank, with no errors. Why is this so? I've also tried doing 'weekends'='False', which still shows the calendar with weekends, so the calendar clearly isn't being configured right when it comes to booleans. I'm not sure why though, since other configuration settings (e.g. header, defaultView, and firstDay) all seemed to have worked fine. 2) I used OrderedDict() because I had a suspicion that the order matters when trying to load events to the calendar, but I'm not sure if this is true. Could I just use a regular Python dictionary?

推荐答案

这是一个基本的概述,你需要做什么。创建一个视图,返回完整日历所期望的JSON数据。这很简单。您可以手动创建自定义的 JsonResponse 或使用Django Rest Framework。除非您正在创建一个完整的API,否则我将使用JsonResponse。

Here's a basic overview of what you need to do. Create a view that returns the JSON data as full calendar expects it. This is pretty simple to do. You can create a custom one by hand with JsonResponse or use Django Rest Framework. Unless you're creating a whole API, I'd go with using JsonResponse.

对于JsonResponse的格式,您需要同时指定开始标题。您可以在完整的日历的文档中找到其他可能的字段。

As for the format of the JsonResponse, you need to specify both start and title. You can find the other possible fields here in full calendar's docs.

示例:

from django.http import JsonResponse

def example(request):
    data = [
        {
            'title': 'event1',
            'start': '2010-01-01'
        },
        {
            'title': 'event2',
            'start': '2010-01-05',
            'end': '2010-01-07'
        }
    ]
    return JsonResponse(data, safe=False)

这篇关于在Django中使用fullCalendar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆