I have two DateTime Fields in a model:
models.py
start_appointment = models.DateTimeField(default=timezone.now, blank=True)
end_appointment = models.DateTimeField(default=timezone.now, blank=True)
i also have a form where i set widgets for above fields:
'start_appointment': forms.DateTimeInput(attrs={'class': 'form-control', 'type': "datetime-local"}),
'end_appointment': forms.DateTimeInput(attrs={'class': 'form-control', 'type': "datetime-local"}),
i have an update view where i want to update appointment's fields for example start_appointment. However when rendering form in a template these two fields are shown as dd/mm/yyyy --:--, --
meaning values from database not shown, while all the others are rendered with no problem.
From the other hand i can execute the form with no problem and update is successful.
template:
<div class="form-group row">
<label class="col-form-label col-3 text-lg-right text-left">{% trans 'Start Appointment' %}</label>
<div class="col-9">
{{ form.start_appointment }}
</div>
</div>
Update
Adding forms.py
class AddAppointmentForm(forms.ModelForm):
class Meta:
model = Appointment
fields = ['user', 'name', 'appointment_notes', 'seat', 'start_appointment', 'end_appointment']
widgets = {
'user': forms.Select(attrs={'class': 'form-control'}),
'name': forms.TextInput(attrs={'class': 'form-control'}),
'appointment_notes': forms.Textarea(attrs={'maxlength': '900', 'class': 'form-control' }),
'seat': forms.Select(attrs={'class': 'form-control'}),
'start_appointment': forms.DateTimeInput(attrs={'class': 'form-control', 'type': "datetime-local"}),
'end_appointment': forms.DateTimeInput(attrs={'class': 'form-control', 'type': "datetime-local"}),
}
What might be the problem?
CodePudding user response:
the problem might be this 'type': "datetime-local"
try this
try to change your datetime to something like this
'start_appointment': forms.DateTimeInput(format='%Y-%m-%d %H:%M:%S', attrs={'class':'datetimefield'})
and for datetimepicker you can use something like this
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script>
window.addEventListener("DOMContentLoaded", function () {
flatpickr(".datetimefield", {
enableTime: true,
enableSeconds: true,
dateFormat: "Y-m-d H:i:S",
});
});
</script>
you can learn more on Flatpickr here https://flatpickr.js.org/