I'm beginning to build a website using Django and I've ran into some issues when trying to update a database. More specifically, I want to use a Flatpickr calendar so that the user can select a date and time and then use that information to populate the "date" field in my form, but I don't know how to do this. I know I could just use a date-time widget for the form field and make it simpler, but I want to use Flatpickr to make it look nicer. I've tried updating the field with JavaScript but it didn't work.
I copy here a section of the code so you can see what I've tried.
First, a piece of the HTML file:
<script>
var calendar = document.getElementById("div_calendar")
flatpickr(calendar, {
enableTime: true,
dateFormat: "Y-m-d H:i",
inline: true,
appendTo: calendar,
onChange: function(selectedDates, dateStr, instance) {
if (selectedDates.length > 0){
//We obtained the first date selected (we assume there is only one)
var dateSelected = selectedDates[0];
// Format the date as a string with the format 'Y-m-d H:i'
var formattedDate = dateSelected.toISOString().slice(0, 16).replace('T', ' ');
// Update the value of the form field
$("#{{ form_bookings.date.id }}").val(formattedDate);
}
}
});
</script>
<div id="div_appointment">
<h2 id="h2_appointment">Book your appointment</h2>
<form id="form_bookings" action="" method="POST">
{% csrf_token %}
{{form}}
<input type="submit" value="Aceptar">
</form>
</div>
The file where I declared the model to use with the form:
from django.db import models
from django.utils import timezone
class Bookings(models.Model):
name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField(max_length=50)
date = models.DateTimeField()
And finally, the code of the file where I declared the form:
from django import forms
from .models import Turnos
class FormBookings(forms.ModelForm):
class Meta:
model = Bookings
fields = "__all__"