示例#1
0
    def to_python(self, value):
        """
        Validates that the input can be converted to a datetime. Returns a
        Python datetime.datetime object.
        """
        if value in self.empty_values:
            return None
        if isinstance(value, datetime.datetime):
            return from_current_timezone(value)
        if isinstance(value, datetime.date):
            result = datetime.datetime(value.year, value.month, value.day)
            return from_current_timezone(result)
        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'],
                                      code='invalid')
            if value[0] in self.empty_values and value[1] in self.empty_values:
                return None
            value = '%s %s' % tuple(value)
        if isinstance(value, float):
            return xlrd.xldate.xldate_as_datetime(value, 0)

        result = super(DateTimeField, self).to_python(value)
        return from_current_timezone(result)
示例#2
0
    def to_python(self, value):
        if value in validators.EMPTY_VALUES:
            return None

        if isinstance(value, list):
            # This came from SplitDateTimeWidget so the value is two strings
            value = ' '.join(value)

        if isinstance(value, str) or isinstance(value, unicode):
            try:
                v = dateutil.parser.parse(value, tzinfos=all_timezones_map())
            except:
                raise ValidationError('Invalid date/time string: %s' % value)

            return from_current_timezone(v)

        if isinstance(value, datetime.datetime):
            return from_current_timezone(value)

        if isinstance(value, datetime.date):
            result = datetime.datetime(value.year, value.month, value.day)
            return from_current_timezone(result)

        raise ValidationError('Unknown data/time field value type: %s' %
                              type(value))
示例#3
0
 def to_python(self, value):
     """
     Validates that the input can be converted to a datetime. Returns a
     Python datetime.datetime object.
     """
     if value in self.empty_values:
         return None
     if isinstance(value, datetime.datetime):
         return from_current_timezone(value)
     if isinstance(value, datetime.date):
         result = datetime.datetime(value.year, value.month, value.day)
         return from_current_timezone(result)
     if isinstance(value, list):
         # Input comes from a SplitDateTimeWidget, for example. So, it's two
         # components: date and time.
         warnings.warn(
             'Using SplitDateTimeWidget with DateTimeField is deprecated. '
             'Use SplitDateTimeField instead.',
             PendingDeprecationWarning, stacklevel=2)
         if len(value) != 2:
             raise ValidationError(self.error_messages['invalid'], code='invalid')
         if value[0] in self.empty_values and value[1] in self.empty_values:
             return None
         value = '%s %s' % tuple(value)
     result = super(DateTimeField, self).to_python(value)
     return from_current_timezone(result)
示例#4
0
文件: fields.py 项目: rparent/django
 def to_python(self, value):
     """
     Validates that the input can be converted to a datetime. Returns a
     Python datetime.datetime object.
     """
     if value in self.empty_values:
         return None
     if isinstance(value, datetime.datetime):
         return from_current_timezone(value)
     if isinstance(value, datetime.date):
         result = datetime.datetime(value.year, value.month, value.day)
         return from_current_timezone(result)
     if isinstance(value, list):
         # Input comes from a SplitDateTimeWidget, for example. So, it's two
         # components: date and time.
         warnings.warn(
             'Using SplitDateTimeWidget with DateTimeField is deprecated. '
             'Use SplitDateTimeField instead.',
             RemovedInDjango19Warning, stacklevel=2)
         if len(value) != 2:
             raise ValidationError(self.error_messages['invalid'], code='invalid')
         if value[0] in self.empty_values and value[1] in self.empty_values:
             return None
         value = '%s %s' % tuple(value)
     result = super(DateTimeField, self).to_python(value)
     return from_current_timezone(result)
示例#5
0
    def to_python(self, value):
        if value in validators.EMPTY_VALUES:
            return None

        if isinstance(value, list):
            # This came from SplitDateTimeWidget so the value is two strings
            value = ' '.join(value)

        if isinstance(value, str) or isinstance(value, unicode):
            try:
                v = dateutil.parser.parse(value, tzinfos=all_timezones_map())
            except:
                raise ValidationError('Invalid date/time string: %s' % value)

            return from_current_timezone(v)

        if isinstance(value, datetime.datetime):
            return from_current_timezone(value)

        if isinstance(value, datetime.date):
            result = datetime.datetime(value.year, value.month, value.day)
            return from_current_timezone(result)

        raise ValidationError('Unknown data/time field value type: %s' %
                              type(value))
示例#6
0
 def to_python(self, value):
     """
     Validates that the input can be converted to a datetime. Returns a
     Python datetime.datetime object.
     """
     if value in self.empty_values:
         return None
     if isinstance(value, datetime.datetime):
         return from_current_timezone(value)
     if isinstance(value, datetime.date):
         result = datetime.datetime(value.year, value.month, value.day)
         return from_current_timezone(result)
     result = super(DateTimeField, self).to_python(value)
     return from_current_timezone(result)
def test_shift_create(admin_webtest_client, factories, models):
    event = factories.EventFactory()
    role = factories.RoleFactory()
    url = reverse('admin:shift-create', kwargs={
        'department_pk': role.department_id,
        'role_pk': role.pk,
    })

    shift_time = (
        datetime.datetime.now().replace(hour=14, minute=0, second=0, microsecond=0) +
        timezone.timedelta(10)
    )

    response = admin_webtest_client.get(url)
    response.form['start_time'] = shift_time.strftime('%Y-%m-%d %H:%M:%S')
    response.form['shift_minutes'] = 120
    response.form['num_slots'] = 5
    response.form['code'] = 'test-code'

    form_response = response.form.submit()
    assert form_response.status_code == 302

    shift = models.Shift.objects.get()
    assert shift.role == role
    assert shift.event == event
    assert shift.start_time == from_current_timezone(shift_time)
    assert shift.shift_minutes == 120
    assert shift.num_slots == 5
    assert shift.code == 'test-code'
示例#8
0
 def to_python(self, value):
     """Produce timezone aware datetime with 00:00:00 as time"""
     value = super(WeblateDateField, self).to_python(value)
     if isinstance(value, date):
         return from_current_timezone(
             datetime(value.year, value.month, value.day, 0, 0, 0))
     return value
示例#9
0
 def form_valid(self, form):
     print(form.data)
     day = form.data.get('date_revue_day')
     month = form.data.get('date_revue_month')
     year = form.data.get('date_revue_year')
     self.date_revue = from_current_timezone(
         datetime.datetime(year=int(year), month=int(month), day=int(day)))
     return super().form_valid(form)
示例#10
0
 def to_python(self, value):
     # First parse from ISO format.
     if value and isinstance(value, str):
         result = parse_datetime(value)
         if result:
             return from_current_timezone(result)
     # If not ISO format then standard behavior.
     return super().to_python(value)
示例#11
0
    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, jdatetime.datetime):
            return from_current_timezone(value)
        if isinstance(value, jdatetime.date):
            result = jdatetime.datetime(value.year, value.month, value.day)
            return from_current_timezone(result)
        if isinstance(value, list):
            # Input comes from a SplitDateTimeWidget, for example. So, it's two
            # components: date and time.
            if len(value) != 2:
                raise exceptions.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)

        groups = re.search(
            r'(?P<year>[\d]{1,4})-(?P<month>[\d]{1,2})-(?P<day>[\d]{1,2}) '
            r'(?P<hour>[\d]{1,2}):(?P<minute>[\d]{1,2})'
            r'(:(?P<second>[\d]{1,2}))?(.(?P<microsecond>[\d]{1,5}))?', value)
        try:
            microsecond = int(groups.group('microsecond') or 0)
            second = int(groups.group('second') or 0)
            result = jdatetime.datetime(
                year=int(groups.group('year')),
                month=int(groups.group('month')),
                day=int(groups.group('day')),
                hour=int(groups.group('hour')),
                minute=int(groups.group('minute')),
                second=second,
                microsecond=microsecond,
            )
            return from_current_timezone(result)

        except (ValueError, AttributeError):
            pass

        raise exceptions.ValidationError(self.error_messages['invalid'])
示例#12
0
 def to_python(self, value):
     """
     Validate that the input can be converted to a datetime. Return a
     Python datetime.datetime object.
     """
     if value in self.empty_values:
         return None
     if isinstance(value, datetime.datetime):
         return from_current_timezone(value)
     if isinstance(value, datetime.date):
         result = datetime.datetime(value.year, value.month, value.day)
         return from_current_timezone(result)
     try:
         result = parse_datetime(value.strip())
     except ValueError:
         raise ValidationError(self.error_messages['invalid'], code='invalid')
     if not result:
         result = super().to_python(value)
     return from_current_timezone(result)
示例#13
0
 def enforce_timezone(self, value):
     """
     When `self.default_timezone` is `None`, always return naive datetimes.
     When `self.default_timezone` is not `None`, always return aware datetimes.
     """
     if (self.default_timezone is not None) and not timezone.is_aware(value):
         return from_current_timezone(value)
     elif (self.default_timezone is None) and timezone.is_aware(value):
         return timezone.make_naive(value, timezone.UTC())
     return value
示例#14
0
 def compress(self, data_list):
     # Differs from the default implementation: If only a time is given and no date, we consider the field empty
     if data_list:
         if data_list[0] in self.empty_values:
             return None
         if data_list[1] in self.empty_values:
             raise ValidationError(self.error_messages['invalid_date'], code='invalid_date')
         result = datetime.datetime.combine(*data_list)
         return from_current_timezone(result)
     return None
示例#15
0
 def compress(self, data_list):
     # Differs from the default implementation: If only a time is given and no date, we consider the field empty
     if data_list:
         if data_list[0] in self.empty_values:
             return None
         if data_list[1] in self.empty_values:
             raise ValidationError(self.error_messages['invalid_date'], code='invalid_date')
         result = datetime.datetime.combine(*data_list)
         return from_current_timezone(result)
     return None
示例#16
0
    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, jdatetime.datetime):
            return from_current_timezone(value)
        if isinstance(value, jdatetime.date):
            result = jdatetime.datetime(value.year, value.month, value.day)
            return from_current_timezone(result)
        if isinstance(value, list):
            # Input comes from a SplitDateTimeWidget, for example. So, it's two
            # components: date and time.
            if len(value) != 2:
                raise exceptions.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)

        groups = re.search(
            r'(?P<year>[\d]{1,4})-(?P<month>[\d]{1,2})-(?P<day>[\d]{1,2}) '
            r'(?P<hour>[\d]{1,2}):(?P<minute>[\d]{1,2})'
            r'(:(?P<second>[\d]{1,2}))?(.(?P<microsecond>[\d]{1,5}))?',
            value
        )
        try:
            microsecond = int(groups.group('microsecond') or 0)
            second = int(groups.group('second') or 0)
            result = jdatetime.datetime(year=int(groups.group('year')),
                                      month=int(groups.group('month')),
                                      day=int(groups.group('day')),
                                      hour=int(groups.group('hour')),
                                      minute=int(groups.group('minute')),
                                      second=second,
                                      microsecond=microsecond)
            return from_current_timezone(result)

        except (ValueError, AttributeError):
            pass

        raise exceptions.ValidationError(self.error_messages['invalid'])
示例#17
0
 def compress(self, data_list):
     if data_list:
         # Raise a validation error if time or date is empty
         # (possible if SplitDateTimeField has required=False).
         if data_list[0] in self.empty_values:
             raise ValidationError(self.error_messages['invalid_date'], code='invalid_date')
         if data_list[1] in self.empty_values:
             raise ValidationError(self.error_messages['invalid_time'], code='invalid_time')
         result = datetime.datetime.combine(*data_list)
         return from_current_timezone(result)
     return None
示例#18
0
    def to_python(self, value):
        value = (value or '').strip()
        if value:
            try:
                dayfirst = not bool(re.match(r'^\d{4}.\d\d?.\d\d?', value)) and not self.middle_endian
                return from_current_timezone(parser.parse(value, dayfirst=dayfirst))
            except (TypeError, ValueError, OverflowError):
                raise forms.ValidationError(self.error_messages['invalid'], code='invalid')

        else:
            return None
示例#19
0
 def compress(self, data_list):
     if data_list:
         # Raise a validation error if time or date is empty
         # (possible if SplitDateTimeField has required=False).
         if data_list[0] in self.empty_values:
             raise ValidationError(self.error_messages['invalid_date'], code='invalid_date')
         if data_list[1] in self.empty_values:
             raise ValidationError(self.error_messages['invalid_time'], code='invalid_time')
         result = datetime.datetime.combine(*data_list)
         return from_current_timezone(result)
     return None
示例#20
0
 def enforce_timezone(self, value):
     """
     When `self.default_timezone` is `None`, always return naive datetimes.
     When `self.default_timezone` is not `None`, always return aware datetimes.
     """
     if (self.default_timezone
             is not None) and not timezone.is_aware(value):
         return from_current_timezone(value)
     elif (self.default_timezone is None) and timezone.is_aware(value):
         return timezone.make_naive(value, timezone.UTC())
     return value
示例#21
0
    def clean(self):
        day = utils.force_aware(self.cleaned_data['day'])
        self.cleaned_data['start_time'] = day + timedelta(
            seconds=self.cleaned_data['start_time_delta'])

        self.cleaned_data['end_time'] = day + timedelta(
            seconds=self.cleaned_data['end_time_delta'])

        dtstart = datetime.combine(
            self.cleaned_data['day'],
            utils.time_from_offset(self.cleaned_data['start_time_delta']))
        self.cleaned_data['start_time'] = from_current_timezone(dtstart)
        dtend = datetime.combine(
            self.cleaned_data['day'],
            utils.time_from_offset(self.cleaned_data['end_time_delta']))
        self.cleaned_data['end_time'] = from_current_timezone(dtend)

        #         print(dtstart)
        #         print(dtend)
        from pprint import pprint
        #         pprint(self.cleaned_data)

        return self.cleaned_data
示例#22
0
 def to_python(self, value):
     """Produce timezone aware datetime with 00:00:00 as time"""
     value = super(WeblateDateField, self).to_python(value)
     if isinstance(value, date):
         return from_current_timezone(
             datetime(
                 value.year,
                 value.month,
                 value.day,
                 0,
                 0,
                 0
             )
         )
     return value
示例#23
0
 def compress(self, data_list):
     """
     On the DateTime widget, we don't want the time to be required, only the date:
     - if the time is not set on a form, we set it to 0:00:00,
     - if only the time is set, we ignore the value.
     """
     if data_list:
         if data_list[0] in self.empty_values:
             # If there is no date, we ignore the time and act as if nothing was submitted
             return None
         if data_list[1] in self.empty_values:
             # If there is a date but no time, we take midnight as default time
             data_list[1] = time(0)
         result = datetime.combine(*data_list)
         return from_current_timezone(result)
     return None
示例#24
0
def parse_datetime_value(value: Any) -> datetime:
    parsed_value = parse_value(value, datetime_input_formats)
    if not parsed_value:
        raise ValueError(_("Enter a valid date/time."))
    return from_current_timezone(parsed_value)
示例#25
0
    def save(self, *args, **kwargs):
#        if self.byweekday:
#            self.byweekday = [str(day) for day in self.byweekday]
        if self.until:
            self.until = from_current_timezone(self.until)
        super(Rule, self).save(*args, **kwargs)
示例#26
0
 def save(self, *args, **kwargs):
     if self.allday == True:
         self.startdatetime = from_current_timezone(datetime(self.startdatetime.year, self.startdatetime.month, self.startdatetime.day))
         self.enddatetime = from_current_timezone(datetime(self.startdatetime.year, self.startdatetime.month, self.startdatetime.day + timedelta(days=1)))
     super(Event, self).save(*args, **kwargs)
示例#27
0
"""