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

问题描述

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

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

当我检查内置的django管理员中的应用程序时,DateField也附加了时间,所以如果你尝试保存它返回一个错误。如何使默认日期? (datetime.today()也不工作)

解决方案

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



您所做的另一个错误是在默认情况下实际调用该函数,使用()。这意味着所有型号都将在类首次定义时获得日期 - 所以如果您的服务器停留数天或数周,而不重新启动Apache,所有元素将在初始日期相同。 p>

所以字段应该是:

  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 it returns an error. 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:

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

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

08-14 03:30