Matt Craig
Matt Craig

Reputation: 33

Set default date with Django SelectDateWidget

Firstly, this question has already been asked here, however the answer does not work, and is also for Django 1.3. Having done extensive research on similar questions on SO, the Django Docs, and general Googling, I still can't find a working answer. Not really a major detail, but it's annoying both when trying to use the form I'm creating, and because I can't solve it.

When using the SelectDateWidget in a ModelForm, I want to be able to set the default on the widget to today's date.

forms.py

from django import forms
from .models import Article
from django.utils import timezone

class ArticleForm(forms.ModelForm):
publish=forms.DateField(widget=forms.SelectDateWidget(), initial = timezone.now)
class Meta:
    model = Article
    fields = [
    'title',

      ...

    'publish',
    ]

models.py

from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.utils import timezone

from Blog.models import Category

class Article(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    title = models.CharField(max_length = 120, unique=True)

      ...

    publish = models.DateField(default=timezone.now)

I'm assuming I have some syntax error somewhere, but have had no joy in finding it.

Upvotes: 1

Views: 1508

Answers (1)

denvaar
denvaar

Reputation: 2214

Looks like there's a subtle difference when setting the the default time for DateTimeField and DateField.

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. So even if you set a value for this field when creating the object, it will be ignored. If you want to be able to modify this field, set the following instead of auto_now_add=True:

For DateField: default=date.today - from datetime.date.today() For DateTimeField: default=timezone.now - from django.utils.timezone.now()

So, you'll want to use date.today rather than timezone.now.

Upvotes: 1

Related Questions