Set today date as default value in the model

狂风中的少年 提交于 2019-12-11 05:47:21

问题


How can I set the default value as today date in a model?

My model: vote_date = models.DateField(_('vote date'), null=False, blank=False)


回答1:


None of the answers solve the original problem. Restating the problem, how can I set the default value of a date field to todays date and still let the user override the default.

From the DJango docs:

DateField.auto_now
Automatically set the field to now every time the object is saved. Useful for "last-modified" timestamps. Note that the current date is always used; it's not just a default value that you can override.

DateField.auto_now_add
Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it's not just a default value that you can override.

The answer if this is not just a "when was this added/edited" field, is to use

default=datetime.date.today

note no parens. This sets the default to the function, not the value returned by the function when the model is evaluated.




回答2:


Use auto_now_add instead, as auto_now would change the vote date any time the object is modified.

http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.DateField.auto_now_add




回答3:


This resolve my problem:

vote_date = models.DateField(_('vote date'), null=False, blank=False, auto_now=True)

More info about django fields...




回答4:


django command extensions can help you with many things like:

  • CreationDateTimeField - DateTimeField that will automatically set it's date when the object is first saved to the database. Works in the same way as the deprecated auto_now_add keyword.
  • ModificationDateTimeField - DateTimeField that will automatically set it's date when an object is saved to the database. Works in the same way as the deprecated auto_now keyword.

http://code.google.com/p/django-command-extensions/



来源:https://stackoverflow.com/questions/5023788/set-today-date-as-default-value-in-the-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!