如何使用Django表单保存日期/时间 [英] How to save date/time with Django form

查看:796
本文介绍了如何使用Django表单保存日期/时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

提交表单时,POST请求数据显示为ridetime_year,ridetime_day和ridetime_month。

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()


推荐答案

好,提交表单时,您将获得 ridetime的值在 cleaned_data 中的作为 datetime 对象,它看起来像将此 2014-11-18 00:00:00 删除。如果您的模型字段为 DateTimeField ,则可以将该对象直接保存到模型中。在views.py中保存 ridetime 的值的方式应该可以正常工作。

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.

因此,使用 SelectDateWidget 只会为您提供提交表单时的日期。如果要保存日期时间,可以尝试这样(使用 DateTimeInput ):

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'))

它将呈现一个TextField,您需要在其中以上述格式输入日期(例如: 2014/11/18 12:12 :00 )。您可以使用 DateTimePicker 之类的JQuery在该文本字段上选择日期时间。 DateTimeInput小部件将为您提供一个datetime对象,其中包含您输入的日期/时间。因此,您可以将其直接保存在模型中。

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.

这篇关于如何使用Django表单保存日期/时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆