JMira
JMira

Reputation: 888

Set today date as default value in the model

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)

Upvotes: 2

Views: 5808

Answers (4)

Dale Wilson
Dale Wilson

Reputation: 9434

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.

Upvotes: 3

panchicore
panchicore

Reputation: 11932

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/

Upvotes: 0

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

Upvotes: 1

JMira
JMira

Reputation: 888

This resolve my problem:

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

More info about django fields...

Upvotes: 0

Related Questions