I just can’t get this working. Continually gives this error:
“[05/Jul/2023 21:49:29] “GET /shift_info_customer/87/ HTTP/1.1” 200 3226
Not Found: /update_shift_status/87/”
I tried this script:
<button type="button" onclick="updateShiftStatus(5, {{ shift.id }})">Update Status</button>
<script>
function updateShiftStatus(newStatus, shiftId) {
// Send an AJAX request to update the shift status
const url = '/update_shift_status/' + shiftId + '/';
const data = {
status: newStatus
};
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': getCookie('csrftoken')
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(result => {
console.log('Shift status updated successfully:', result);
})
.catch(error => {
console.error('Error updating shift status:', error);
});
}
// Function to retrieve the value of a cookie
function getCookie(name) {
const value = '; ' + document.cookie;
const parts = value.split('; ' + name + '=');
if (parts.length === 2) {
return parts.pop().split(';').shift();
}
}
</script>
This is the view:
def update_shift_status(request, shift_id):
if request.method == 'POST':
status_id = request.POST.get('status_id')
shift = get_object_or_404(Shift, id=shift_id)
status = get_object_or_404(Status, id=status_id) # Retrieve the Status object
shift.status = status # Assign the new status object
shift.save()
return JsonResponse({'message': 'Shift status updated successfully.'})
else:
return JsonResponse({'message': 'Invalid request.'}, status=400)
I modified my view to handle JSON data. Now it works. Thanks for pointing this out Ken!
Here is my view now:
def update_shift_status(request, shift_id):
if request.method == 'POST':
data = json.loads(request.body)
status_id = data.get('status')
if status_id is not None:
try:
shift = Shift.objects.get(id=shift_id)
status = Status.objects.get(id=status_id)
shift.status = status
shift.save()
return JsonResponse({'message': 'Shift status updated successfully.'})
except (Shift.DoesNotExist, Status.DoesNotExist):
return JsonResponse({'message': 'Shift or Status does not exist.'}, status=404)
else:
return JsonResponse({'message': 'Invalid request. Missing status ID.'}, status=400)
else:
return JsonResponse({'message': 'Invalid request. Must be a POST request.'}, status=400)