Automatically sets date to today if only time part was entered. If today is 01/01/2008, then both DateTimeField and TodayDateTimeField clean '2008-01-01 15:05' to datetime(2008,01,01,15,5,0), while '15:05' is cleaned as datetime(1900,01,01,15,5,0) for DateTimeField but datetime(2008,01,01,15,5,0) for 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)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 8 months ago
Comments
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?
#
Please login first before commenting.