Variation on SplitDateTimeField that does not enforce the Time to be required, accepting a default instead.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | class NonTimeSplitDateTimeField(forms.SplitDateTimeField):
"""Variation on SplitDateTimeField that does not enforce the Time to be
required, accepting a default instead.
example usage:
class MonkeyForm(forms.ModelForm):
start_date = NonTimeSplitDateTimeField(
default_time=datetime.time(00,00,00),
widget=widgets.AdminSplitDateTime(), required=False )
end_date = NonTimeSplitDateTimeField(
default_time=datetime.time(11,59,59),
widget=widgets.AdminSplitDateTime(), required=False )
"""
def __init__(self, default_time, *args, **kwargs):
self.default_time = default_time
return super(NonTimeSplitDateTimeField, self).__init__(
*args, **kwargs)
def compress(self, data_list):
if data_list:
# Raise a validation error if date is empty
# (possible if SplitDateTimeField has required=False).
if data_list[0] in EMPTY_VALUES:
raise ValidationError(self.error_messages['invalid_date'])
if data_list[1] in EMPTY_VALUES:
# Rather than raising an error (as super does) use the
# default time passed in the constructor
data_list[1] = self.default_time
return datetime.datetime.combine(*data_list)
return None
|
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, 7 months ago
Comments
Please login first before commenting.