Set today date as default value in the model

2019-08-03 17:09发布

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)

4条回答
女痞
2楼-- · 2019-08-03 17:46

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楼-- · 2019-08-03 17:47

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/

查看更多
\"骚年 ilove
4楼-- · 2019-08-03 17:50

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.

查看更多
Melony?
5楼-- · 2019-08-03 18:02

This resolve my problem:

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

More info about django fields...

查看更多
登录 后发表回答