Django DateField 默认选项 [英] Django DateField default options

查看:34
本文介绍了Django DateField 默认选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有日期时间字段的模型:

date = models.DateField(_("Date"), default=datetime.now())

当我在内置的 django admin 中检查应用程序时,DateField 还附加了时间,因此如果您尝试保存它,则会返回错误.如何将默认设置设为日期?(datetime.today() 也不起作用)

解决方案

这就是为什么你应该总是导入基本的 datetime 模块:import datetime,而不是该模块中的 datetime 类:from datetime import datetime.

您犯的另一个错误是使用() 在默认情况下实际调用该函数.这意味着所有模型都将在第一次定义类时获取日期 - 因此,如果您的服务器在没有重新启动 Apache 的情况下保持运行数天或数周,所有元素将获得相同的初始日期.>

所以字段应该是:

导入日期时间date = models.DateField(_("Date"), default=datetime.date.today)

I have a model which has a date time field:

date = models.DateField(_("Date"), default=datetime.now())

When I check the app in the built in django admin, the DateField also has the time appended to it, so that if you try to save it an error is returned. How do I make the default just the date? (datetime.today() isn't working either)

解决方案

This is why you should always import the base datetime module: import datetime, rather than the datetime class within that module: from datetime import datetime.

The other mistake you have made is to actually call the function in the default, with the (). This means that all models will get the date at the time the class is first defined - so if your server stays up for days or weeks without restarting Apache, all elements will get same the initial date.

So the field should be:

import datetime
date = models.DateField(_("Date"), default=datetime.date.today)

这篇关于Django DateField 默认选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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