TodayDateTimeField

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from django.newforms import DateTimeField, TimeField
from django.newforms.util import ValidationError
import datetime

class TodayDateTimeField(DateTimeField):
    '''
    DateTimeField which sets today's date
    if only time was entered

    '''
    def clean(self, value):
        try:
            t = TimeField().clean(value)
        except ValidationError:
            # try parent's constructor
            return super(TodayDateTimeField,self).clean(value)
        else:
            return datetime.datetime.combine(datetime.date.today(),t)

Comments

KpoH (on April 21, 2008):

Didn't you hear about auto_now=True? Take a look

http://www.djangoproject.com/documentation/model-api/#datefield

#

leotr (on April 24, 2008):

Hello!

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.

First of all, this field is a form field, not a model field. Also my field DOES NOT set automatically current date. The field behaves like this:

For example, today is 1st January 2008. If user enters '2008-01-01 15:05' it behaves like regular DateTimeField. What if i enter just '15:05'? Regular DateTimeField would return '1900-01-01 15:05', while TodayDateTimeField returns '2008-01-01 15:05'.

If somebody could suggest a better description for this snippet?

#

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.