Hello.
I am trying to create a To do list app where the user(s) will enter the task they want to achieve and its starting and ending time.
I have a (model) form containing four fields (title, detail, start_time, end_time).
I want the user to specify the datetime in ‘j n y g:i A’ format (for instance if I were to start a task on 10th June 8:10 pm I would have to write 10 6 23 8:10 PM).
The ModelForm is as under:
class TaskForm(ModelForm):
class Meta:
model = TaskModel
exclude = ["completed"]
widgets = {
'title': TextInput(attrs={"class": "form-control"} ),
'detail': Textarea(attrs={"class": "form-control"}),
'start_time': DateInput(format = settings.DATETIME_FORMAT, attrs={"class": "datepicker"}),
'end_time': DateInput(format = settings.DATETIME_FORMAT, attrs={'class': 'datepicker'})
}
And the TaskModel is:
class TaskModel(models.Model):
title = models.CharField(max_length=30)
detail = models.TextField(blank=True)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
completed = models.BooleanField(blank = True, null=True)
def save(self, *args, **kwargs):
start_time_obj = datetime.strptime(self.start_time, format = settings.DATETIME_FORMAT)
end_time_obj = datetime.strptime(self.end_time, format = settings.DATETIME_FORMAT)
print(start_time_obj)
super(TaskModel, self).save(*args, **kwargs)
Now when I enter the date in the aforementioned format, the validation error occurs:
Invalid date/time format.
I am trying to override the save method of the model so that the input datetime is converted to proper datetime Python object for the item to be saved. But it is not working.
Also if I just print the start_time_obj, I get nothing printed.
In the Django Admin, the date is still picked in the Django’s prescribed format (YYYY-mm-dd…)
Any help will be appreciated.