Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save date/time with Django form

Tags:

django

When I submit a form, the POST request data is shown as ridetime_year,ridetime_day, and ridetime_month.

How I capture the date/time from my form and save it to the DB? Thanks

Forms.py

class AddRideSpot(forms.Form):

    ridetime = forms.DateTimeField(widget=SelectDateWidget,initial=datetime.date.today())

    def clean(self):
        cleaned_data = self.cleaned_data

        ridetime = cleaned_data.get("ridetime")
        return cleaned_data

views.py

def add_point(request):

    if request.method == 'POST':
        form = forms.AddRideSpot(request.POST)
        if form.is_valid():

            cd = form.cleaned_data

            new_ride = models.Ride()

            new_ride.ridetime = cd['ridetime']

            new_ride.save()
like image 372
RustyShackleford Avatar asked Dec 03 '25 09:12

RustyShackleford


1 Answers

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.

like image 126
ruddra Avatar answered Dec 04 '25 23:12

ruddra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!