[Django]-How to save date/time with Django form

3👍

Well, when you submit the form, you will get the value for ridetime in cleaned_data as an datetime object which will look like this 2014-11-18 00:00:00. You can save that object directly to model if your model field is DateTimeField. The way you are saving the value of ridetime in views.py should work fine.

So using SelectDateWidget will only get you the date when you submit the form. If you want to save the datetime, you can try like this (using DateTimeInput):

ridetime = forms.DateTimeField(input_formats=['%d/%m/%Y %H:%M:%S'], widget=forms.DateTimeInput(format='%d/%m/%Y %H:%M:%S'))

It will render a TextField where you need to input the date in the format mentioned above(example: 18/11/2014 12:12:00). You can use JQuery like DateTimePicker to select datetime on that text field. The DateTimeInput Widget will give you a datetime object which contains your inputted date/time. So you can save it directly in the models.

👤ruddra

Leave a comment