The events in fullcalendar sometimes duplicate on my database when moved to another date/time

I'm using fullcalendar 6.1.14 in django 4.2.11. I have a function defined to update the delivery date of an item where the number of the document of the item is the same as the event id, and the year is the year from which it is being changed. I even have a check for it to not add already existing NumDoc + Year combinations. But sometimes, seemingly randomly, it duplicates the event in the database when I drag it to a new date, and I have no idea how to solve this. I'm using Microsoft MySQL Server Management as my database manager.

Function to move events in views.py

@csrf_exempt
def update_delivery_date(request):
    if request.method == 'POST':
        event_id = request.POST.get('id')
        new_start_date = request.POST.get('new_start_date')
        year = request.POST.get('year')
        
        # Check if the user has the allowed groups
        if not (request.user.groups.filter(name__in=['Expedicao', 'Dir Logistica', 'Logistica']).exists() or request.user.is_superuser):
            return JsonResponse({'success': False, 'error': 'User does not have permission to move events'}, status=403)

        try:
            with transaction.atomic():
                # Find the specific event by DocNum and Year
                event = EncomendasCalendar.objects.select_for_update().get(NumDoc=event_id, Ano=year)
                
                # Check if there is already another event with the same DocNum and Year
                if EncomendasCalendar.objects.filter(NumDoc=event_id, Ano=year).exclude(NumDoc=event_id).exists():
                    print("Duplicate")
                    return JsonResponse({'success': False, 'error': 'An event with the same DocNum and Year already exists'}, status=400)
        
                # Check if the new date is the same as the current one
                if event.DataEntrega == new_start_date:
                    print("same")
                    return JsonResponse({'success': False, 'error': 'The delivery date is already the same as the informed date.'}, status=400)
                
                # Update the DeliveryDate with the new date
                event.DataEntrega = new_start_date
                event.UpdatedBy = request.user
                
                # Save the updated event in the database
                event.save()
                
        except EncomendasCalendar.DoesNotExist:
            return JsonResponse({'success': False, 'error': 'Event not found'}, status=404)
        
        except Exception as e:
            print('Error updating the delivery date:', e)
            return JsonResponse({'success': False, 'error': 'Error updating the delivery date'})
        
        return JsonResponse({'success': True})
    else:
        return JsonResponse({'success': False, 'error': 'Method not allowed'}, status=405)

Function in js file where the calendar and the events are moved (calendar.js)

eventDrop: function (info) {
    // Get the ID of the moved event
    var eventId = info.event.id;
    var eventYear = info.event.extendedProps.year;
    // Get the new start date of the moved event
    var newStartDate = info.event.start.toISOString().replace('T', ' ');
    newStartDate = newStartDate.replace('Z', '');

    // Update the delivery date on the server using AJAX
    var csrftoken = Cookies.get('csrftoken');
    $.ajax({
        type: 'POST',
        url: 'update_delivery_date/',
        data: {
            id: eventId,
            new_start_date: newStartDate,
            year: eventYear
        },
        beforeSend: function(xhr) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        },
        success: function(response) {
            // Successful update
        },
        error: function(xhr, status, error) {
            if (xhr.status === 403) {
                // Display a custom error message if the user does not have permission
                alert('Error: You do not have permission to move this event.');
                info.revert();
            } else {
                // In case of an error
                console.error('Error updating the delivery date:', error);
            }
        }
    });
}

Design of the table where Encomendas are inserted, updated etc

normal update

duplication event

I tried many things that I no longer remember, but the last attempt was a check in the views.py code that was supposed to not add a event if the numdoc + year already existed, but it didn't work.

Back to Top