Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import datetime
- from django import forms
- from django.core import validators
- from django.core.exceptions import ValidationError
- from django.utils import six
- from django.utils.encoding import force_text
- class DateTimeNoTimeZoneField(forms.DateTimeField):
- def to_python(self, value):
- """
- Validates that the input can be converted to a datetime. Returns a
- Python datetime.datetime object.
- """
- if value in validators.EMPTY_VALUES:
- return None
- if isinstance(value, datetime.datetime):
- return value
- if isinstance(value, datetime.date):
- return datetime.datetime(value.year, value.month, value.day)
- if isinstance(value, list):
- # Input comes from a SplitDateTimeWidget, for example. So, it's two
- # components: date and time.
- if len(value) != 2:
- raise ValidationError(self.error_messages['invalid'])
- if value[0] in validators.EMPTY_VALUES and value[1] in validators.EMPTY_VALUES:
- return None
- value = '%s %s' % tuple(value)
- # Try to coerce the value to unicode.
- unicode_value = force_text(value, strings_only=True)
- if isinstance(unicode_value, six.text_type):
- value = unicode_value.strip()
- # If unicode, try to strptime against each input format.
- if isinstance(value, six.text_type):
- for format in self.input_formats:
- try:
- return self.strptime(value, format)
- except (ValueError, TypeError):
- continue
- raise ValidationError(self.error_messages['invalid'])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement