I'm building an app to schedule events on Google Calendar using Django, and I'm encountering an issue with sending data via a POST request to a Django view. Here's my Django view code for CreateEventFunc:
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
@csrf_exempt
def CreateEventFunc(request):
# For debugging purposes, write data to a file
with open('output.txt', 'w') as file:
file.write("CreateEventFunc\n")
if request.method == 'POST':
data = json.loads(request.body.decode('utf-8'))
therapist_id = data['therapist_id']
start_time = data['start_time']
end_time = data['end_time']
# Create the event using your utility function (e.g., create_event)
# Replace this with your actual implementation
created_event = create_event(therapist_id, 'Appointment', start_time, end_time)
# Return a response (you can customize this based on your needs)
response_data = {'message': 'Event created successfully', 'event_id': created_event['id']}
return JsonResponse(response_data)
On the frontend, I have a JavaScript function scheduleMeeting that sends a POST request to this view when a meeting is scheduled:
<script>
function scheduleMeeting(startTime, endTime, therapistId) {
if(confirm("Do you want to schedule a meeting from " + startTime + " to " + endTime + "?")) {
// Create a data object to send with the POST request
var eventData = {
'start_time': startTime,
'end_time': endTime,
'therapist_id': therapistId,
};
// Send a POST request to the server to create the event
$.ajax({
type: 'POST',
url: '/create_event/', // Update the URL to the actual endpoint
data: JSON.stringify(eventData),
contentType: 'application/json; charset=utf-8',
success: function(response) {
// Handle the success response from the server, if needed
alert('Event created successfully!');
},
error: function(error) {
// Handle any errors, if needed
alert('Error creating the event.');
}
});
}
}
</script>
I've added some debugging code to write to a file, but it doesn't seem to be writing the expected data. I suspect the issue might be related to how I'm handling Ajax. Can someone please help me identify the issue, especially considering my limited experience with Ajax, and explain how I can fix it? The ultimate goal is to create events on Google Calendar.