FullCalendar in Django

前端 未结 2 496
孤独总比滥情好
孤独总比滥情好 2020-12-01 05:10

So, I have an appointment models

class Appointment(models.Model):
    user = models.ForeignKey(User)
    date = models.DateField()
    time = models.TimeFie         


        
相关标签:
2条回答
  • 2020-12-01 05:18

    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 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:

    url('^calendar', views.calendar, name='calendar'),
    url('^add_event$', views.add_event, name='add_event'),
    url('^update$', views.update, name='update'),
    url('^remove', views.remove, name='remove'),
    

    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: [
                        {% for event in events %}
                            {
                                title: "{{ event.name}}",
                                start: '{{ event.start|date:"Y-m-d" }}',
                                end: '{{ event.end|date:"Y-m-d" }}',
                                id: '{{ event.id }}',
                            },
                        {% endfor %}
                    ],
                    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");
                                },
                                failure: 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');
                            },
                            failure: 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');
                            },
                            failure: 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');
                                },
                                failure: 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})
    
    0 讨论(0)
  • 2020-12-01 05:43

    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");
                    }
    
    
                })
                })
    
        })
    
    0 讨论(0)
提交回复
热议问题