Python django.forms.DateField() Examples

The following are 30 code examples of django.forms.DateField(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.forms , or try the search function .
Example #1
Source File: test_widgets_django.py    From django-sniplates with MIT License 6 votes vote down vote up
def test_date_input_different_format(self):
        """
        Tests that the ``django.forms`` configured input format is respected.
        """
        class Form(forms.Form):
            date = forms.DateField(widget=forms.DateInput(format='%m-%Y-%d'))

        self.ctx['form'] = Form(initial={'date': datetime.date(2016, 3, 27)})
        tmpl = get_template('widgets_django')
        output = tmpl.render(self.ctx)
        self.assertHTMLEqual(
            output,
            '<input type="text" name="date" id="id_date" value="03-2016-27" class=" " required>'
        ) 
Example #2
Source File: forms.py    From ideascube with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        for name, field in self.fields.items():
            if isinstance(field, forms.DateField):
                # Force date format on load, so date picker doesn't mess it up
                # because of i10n.
                field.widget = forms.DateInput(format='%Y-%m-%d')

            if name == 'extra':
                field.label = getattr(
                    settings, 'USER_EXTRA_FIELD_LABEL', _('Additional data')) 
Example #3
Source File: test_input_formats.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_dateField(self):
        "DateFields can parse dates in the default format"
        f = forms.DateField()
        # Parse a date in an unaccepted format; get an error
        with self.assertRaises(forms.ValidationError):
            f.clean('21/12/2010')

        # ISO formats are accepted, even if not specified in formats.py
        self.assertEqual(f.clean('2010-12-21'), date(2010, 12, 21))

        # Parse a date in a valid format, get a parsed result
        result = f.clean('21.12.2010')
        self.assertEqual(result, date(2010, 12, 21))

        # The parsed result does a round trip
        text = f.widget.format_value(result)
        self.assertEqual(text, '21.12.2010')

        # Parse a date in a valid, but non-default format, get a parsed result
        result = f.clean('21.12.10')
        self.assertEqual(result, date(2010, 12, 21))

        # The parsed result does a round trip to default format
        text = f.widget.format_value(result)
        self.assertEqual(text, "21.12.2010") 
Example #4
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_default_selectdatewidget(self):
        class PubForm(forms.ModelForm):
            date_published = forms.DateField(required=False, widget=forms.SelectDateWidget)

            class Meta:
                model = PublicationDefaults
                fields = ('date_published',)

        mf1 = PubForm({})
        self.assertEqual(mf1.errors, {})
        m1 = mf1.save(commit=False)
        self.assertEqual(m1.date_published, datetime.date.today())

        mf2 = PubForm({'date_published_year': '2010', 'date_published_month': '1', 'date_published_day': '1'})
        self.assertEqual(mf2.errors, {})
        m2 = mf2.save(commit=False)
        self.assertEqual(m2.date_published, datetime.date(2010, 1, 1)) 
Example #5
Source File: test_input_formats.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_localized_dateField_with_inputformat(self):
        "Localized DateFields with manually specified input formats can accept those formats"
        f = forms.DateField(input_formats=["%d.%m.%Y", "%d-%m-%Y"], localize=True)
        # Parse a date in an unaccepted format; get an error
        with self.assertRaises(forms.ValidationError):
            f.clean('2010-12-21')

        # Parse a date in a valid format, get a parsed result
        result = f.clean('21.12.2010')
        self.assertEqual(result, date(2010, 12, 21))

        # The parsed result does a round trip to the same format
        text = f.widget.format_value(result)
        self.assertEqual(text, "2010-12-21")

        # Parse a date in a valid format, get a parsed result
        result = f.clean('21-12-2010')
        self.assertEqual(result, date(2010, 12, 21))

        # The parsed result does a round trip to default format
        text = f.widget.format_value(result)
        self.assertEqual(text, "2010-12-21") 
Example #6
Source File: test_input_formats.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_localized_dateField_with_inputformat(self):
        "Localized DateFields with manually specified input formats can accept those formats"
        f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"], localize=True)
        # Parse a date in an unaccepted format; get an error
        with self.assertRaises(forms.ValidationError):
            f.clean('21.12.2010')
        with self.assertRaises(forms.ValidationError):
            f.clean('2010-12-21')

        # Parse a date in a valid format, get a parsed result
        result = f.clean('12.21.2010')
        self.assertEqual(result, date(2010, 12, 21))

        # The parsed result does a round trip to the same format
        text = f.widget.format_value(result)
        self.assertEqual(text, "21.12.2010")

        # Parse a date in a valid format, get a parsed result
        result = f.clean('12-21-2010')
        self.assertEqual(result, date(2010, 12, 21))

        # The parsed result does a round trip to default format
        text = f.widget.format_value(result)
        self.assertEqual(text, "21.12.2010") 
Example #7
Source File: test_input_formats.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_dateField_with_inputformat(self):
        "DateFields with manually specified input formats can accept those formats"
        f = forms.DateField(input_formats=["%d.%m.%Y", "%d-%m-%Y"])
        # Parse a date in an unaccepted format; get an error
        with self.assertRaises(forms.ValidationError):
            f.clean('2010-12-21')

        # Parse a date in a valid format, get a parsed result
        result = f.clean('21.12.2010')
        self.assertEqual(result, date(2010, 12, 21))

        # The parsed result does a round trip to the same format
        text = f.widget.format_value(result)
        self.assertEqual(text, "2010-12-21")

        # Parse a date in a valid format, get a parsed result
        result = f.clean('21-12-2010')
        self.assertEqual(result, date(2010, 12, 21))

        # The parsed result does a round trip to default format
        text = f.widget.format_value(result)
        self.assertEqual(text, "2010-12-21") 
Example #8
Source File: test_input_formats.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_dateField(self):
        "DateFields can parse dates in the default format"
        f = forms.DateField()
        # Parse a date in an unaccepted format; get an error
        with self.assertRaises(forms.ValidationError):
            f.clean('21.12.2010')

        # Parse a date in a valid format, get a parsed result
        result = f.clean('2010-12-21')
        self.assertEqual(result, date(2010, 12, 21))

        # The parsed result does a round trip to the same format
        text = f.widget.format_value(result)
        self.assertEqual(text, "2010-12-21")

        # Parse a date in a valid, but non-default format, get a parsed result
        result = f.clean('12/21/2010')
        self.assertEqual(result, date(2010, 12, 21))

        # The parsed result does a round trip to default format
        text = f.widget.format_value(result)
        self.assertEqual(text, "2010-12-21") 
Example #9
Source File: test_input_formats.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_dateField_with_inputformat(self):
        "DateFields with manually specified input formats can accept those formats"
        f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"])
        # Parse a date in an unaccepted format; get an error
        with self.assertRaises(forms.ValidationError):
            f.clean('21.12.2010')
        with self.assertRaises(forms.ValidationError):
            f.clean('2010-12-21')

        # Parse a date in a valid format, get a parsed result
        result = f.clean('12.21.2010')
        self.assertEqual(result, date(2010, 12, 21))

        # The parsed result does a round trip to the same format
        text = f.widget.format_value(result)
        self.assertEqual(text, "21.12.2010")

        # Parse a date in a valid format, get a parsed result
        result = f.clean('12-21-2010')
        self.assertEqual(result, date(2010, 12, 21))

        # The parsed result does a round trip to default format
        text = f.widget.format_value(result)
        self.assertEqual(text, "21.12.2010") 
Example #10
Source File: test_input_formats.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_localized_dateField(self):
        "Localized DateFields act as unlocalized widgets"
        f = forms.DateField(localize=True)
        # Parse a date in an unaccepted format; get an error
        with self.assertRaises(forms.ValidationError):
            f.clean('2010-12-21')

        # Parse a date in a valid format, get a parsed result
        result = f.clean('21.12.2010')
        self.assertEqual(result, date(2010, 12, 21))

        # The parsed result does a round trip to the same format
        text = f.widget.format_value(result)
        self.assertEqual(text, '21.12.2010')

        # Parse a date in a valid format, get a parsed result
        result = f.clean('21-12-2010')
        self.assertEqual(result, date(2010, 12, 21))

        # The parsed result does a round trip to default format
        text = f.widget.format_value(result)
        self.assertEqual(text, "21.12.2010") 
Example #11
Source File: filter.py    From django-admin-rangefilter with MIT License 6 votes vote down vote up
def _get_form_fields(self):
        return OrderedDict(
            (
                (self.lookup_kwarg_gte, forms.DateField(
                    label='',
                    widget=AdminDateWidget(attrs={'placeholder': _('From date')}),
                    localize=True,
                    required=False,
                    initial=self.default_gte,
                )),
                (self.lookup_kwarg_lte, forms.DateField(
                    label='',
                    widget=AdminDateWidget(attrs={'placeholder': _('To date')}),
                    localize=True,
                    required=False,
                    initial=self.default_lte,
                )),
            )
        ) 
Example #12
Source File: test_input_formats.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_dateField(self):
        "DateFields can parse dates in the default format"
        f = forms.DateField()
        # Parse a date in an unaccepted format; get an error
        with self.assertRaises(forms.ValidationError):
            f.clean('2010-12-21')

        # Parse a date in a valid format, get a parsed result
        result = f.clean('21.12.2010')
        self.assertEqual(result, date(2010, 12, 21))

        # The parsed result does a round trip
        text = f.widget.format_value(result)
        self.assertEqual(text, '21.12.2010')

        # Parse a date in a valid, but non-default format, get a parsed result
        result = f.clean('21-12-2010')
        self.assertEqual(result, date(2010, 12, 21))

        # The parsed result does a round trip to default format
        text = f.widget.format_value(result)
        self.assertEqual(text, "21.12.2010") 
Example #13
Source File: feature_field_mixin.py    From urbanfootprint with GNU General Public License v3.0 6 votes vote down vote up
def field_map(path, field_class_path):
        """
            Maps paths to a lambda that converts a value of that path
            to a human readable type. Dates are formatted and
            related objects called object.label
            :param path: The simple or concatinated path to a field
            :param field_class_path: A string representation of the field class
        """
        resolved_field_class = resolve_module_attr(field_class_path)
        if issubclass(resolved_field_class, DateField):
            # Convert to localtime (tzinfo for client will need to be specified in settings or passed from client)
            # We need to convert the timezone offset from [-]HHMM to [-]HH:MM to match javascript's format
            return [path, lambda date: date and re.sub(
                r'(\d{2})(\d{2})$',
                r'\1:\2',
                date.astimezone(tzlocal()).strftime("%Y-%m-%dT%H:%M:%S%z"))
            ]
        if issubclass(resolved_field_class, RelatedField):
            # Insist that the related instances have a label property to present to
            # the user. Use the string format as a last resort
            return [path, FeatureFieldMixin.resolve_instance_label]
        return None 
Example #14
Source File: test_input_formats.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_localized_dateField(self):
        "Localized DateFields act as unlocalized widgets"
        f = forms.DateField(localize=True)
        # Parse a date in an unaccepted format; get an error
        with self.assertRaises(forms.ValidationError):
            f.clean('21/12/2010')

        # Parse a date in a valid format, get a parsed result
        result = f.clean('21.12.2010')
        self.assertEqual(result, date(2010, 12, 21))

        # The parsed result does a round trip to the same format
        text = f.widget.format_value(result)
        self.assertEqual(text, '21.12.2010')

        # Parse a date in a valid format, get a parsed result
        result = f.clean('21.12.10')
        self.assertEqual(result, date(2010, 12, 21))

        # The parsed result does a round trip to default format
        text = f.widget.format_value(result)
        self.assertEqual(text, "21.12.2010") 
Example #15
Source File: test_input_formats.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_dateField(self):
        "DateFields can parse dates in the default format"
        f = forms.DateField()
        # Parse a date in an unaccepted format; get an error
        with self.assertRaises(forms.ValidationError):
            f.clean('21/12/2010')

        # ISO formats are accepted, even if not specified in formats.py
        self.assertEqual(f.clean('2010-12-21'), date(2010, 12, 21))

        # Parse a date in a valid format, get a parsed result
        result = f.clean('21.12.2010')
        self.assertEqual(result, date(2010, 12, 21))

        # The parsed result does a round trip
        text = f.widget.format_value(result)
        self.assertEqual(text, '21.12.2010')

        # Parse a date in a valid, but non-default format, get a parsed result
        result = f.clean('21.12.10')
        self.assertEqual(result, date(2010, 12, 21))

        # The parsed result does a round trip to default format
        text = f.widget.format_value(result)
        self.assertEqual(text, "21.12.2010") 
Example #16
Source File: test_edit_handlers.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_get_form_for_model(self):
        EventPageForm = get_form_for_model(EventPage, form_class=WagtailAdminPageForm)
        form = EventPageForm()

        # form should be a subclass of WagtailAdminModelForm
        self.assertTrue(issubclass(EventPageForm, WagtailAdminModelForm))
        # form should contain a title field (from the base Page)
        self.assertEqual(type(form.fields['title']), forms.CharField)
        # and 'date_from' from EventPage
        self.assertEqual(type(form.fields['date_from']), forms.DateField)
        # the widget should be overridden with AdminDateInput as per FORM_FIELD_OVERRIDES
        self.assertEqual(type(form.fields['date_from'].widget), AdminDateInput)

        # treebeard's 'path' field should be excluded
        self.assertNotIn('path', form.fields)

        # all child relations become formsets by default
        self.assertIn('speakers', form.formsets)
        self.assertIn('related_links', form.formsets) 
Example #17
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_default_selectdatewidget(self):
        class PubForm(forms.ModelForm):
            date_published = forms.DateField(required=False, widget=forms.SelectDateWidget)

            class Meta:
                model = PublicationDefaults
                fields = ('date_published',)

        mf1 = PubForm({})
        self.assertEqual(mf1.errors, {})
        m1 = mf1.save(commit=False)
        self.assertEqual(m1.date_published, datetime.date.today())

        mf2 = PubForm({'date_published_year': '2010', 'date_published_month': '1', 'date_published_day': '1'})
        self.assertEqual(mf2.errors, {})
        m2 = mf2.save(commit=False)
        self.assertEqual(m2.date_published, datetime.date(2010, 1, 1)) 
Example #18
Source File: test_edit_handlers.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_get_form_for_model_with_excluded_fields(self):
        EventPageForm = get_form_for_model(
            EventPage, form_class=WagtailAdminPageForm,
            exclude=['title'], exclude_formsets=['related_links'])
        form = EventPageForm()

        # form should contain date_from but not title
        self.assertEqual(type(form.fields['date_from']), forms.DateField)
        self.assertEqual(type(form.fields['date_from'].widget), AdminDateInput)
        self.assertNotIn('title', form.fields)

        # 'path' is not excluded any more, as the excluded fields were overridden
        self.assertIn('path', form.fields)

        # formsets should include speakers but not related_links
        self.assertIn('speakers', form.formsets)
        self.assertNotIn('related_links', form.formsets) 
Example #19
Source File: test_input_formats.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_dateField(self):
        "DateFields can parse dates in the default format"
        f = forms.DateField()
        # Parse a date in an unaccepted format; get an error
        with self.assertRaises(forms.ValidationError):
            f.clean('2010-12-21')

        # Parse a date in a valid format, get a parsed result
        result = f.clean('21.12.2010')
        self.assertEqual(result, date(2010, 12, 21))

        # The parsed result does a round trip
        text = f.widget.format_value(result)
        self.assertEqual(text, '21.12.2010')

        # Parse a date in a valid, but non-default format, get a parsed result
        result = f.clean('21-12-2010')
        self.assertEqual(result, date(2010, 12, 21))

        # The parsed result does a round trip to default format
        text = f.widget.format_value(result)
        self.assertEqual(text, "21.12.2010") 
Example #20
Source File: __init__.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def formfield(self, **kwargs):
        defaults = {'form_class': forms.DateField}
        defaults.update(kwargs)
        return super(DateField, self).formfield(**defaults) 
Example #21
Source File: widgets.py    From opentaps_seas with GNU Lesser General Public License v3.0 5 votes vote down vote up
def make_custom_datefields(f, **kwargs):
    if isinstance(f, models.DateTimeField):
        # return form field with your custom widget here...
        return f.formfield(form_class=DateTimeField, **kwargs)
    elif isinstance(f, models.DateField):
        # return form field with your custom widget here...
        return f.formfield(form_class=DateField, **kwargs)
    else:
        return f.formfield(**kwargs) 
Example #22
Source File: __init__.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def pre_save(self, model_instance, add):
        if self.auto_now or (self.auto_now_add and add):
            value = datetime.date.today()
            setattr(model_instance, self.attname, value)
            return value
        else:
            return super(DateField, self).pre_save(model_instance, add) 
Example #23
Source File: __init__.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def get_internal_type(self):
        return "DateField" 
Example #24
Source File: __init__.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def contribute_to_class(self, cls, name, **kwargs):
        super(DateField, self).contribute_to_class(cls, name, **kwargs)
        if not self.null:
            setattr(cls, 'get_next_by_%s' % self.name,
                curry(cls._get_next_or_previous_by_FIELD, field=self,
                      is_next=True))
            setattr(cls, 'get_previous_by_%s' % self.name,
                curry(cls._get_next_or_previous_by_FIELD, field=self,
                      is_next=False)) 
Example #25
Source File: __init__.py    From python2017 with MIT License 5 votes vote down vote up
def __init__(self, verbose_name=None, name=None, auto_now=False,
                 auto_now_add=False, **kwargs):
        self.auto_now, self.auto_now_add = auto_now, auto_now_add
        if auto_now or auto_now_add:
            kwargs['editable'] = False
            kwargs['blank'] = True
        super(DateField, self).__init__(verbose_name, name, **kwargs) 
Example #26
Source File: __init__.py    From python2017 with MIT License 5 votes vote down vote up
def deconstruct(self):
        name, path, args, kwargs = super(DateField, self).deconstruct()
        if self.auto_now:
            kwargs['auto_now'] = True
        if self.auto_now_add:
            kwargs['auto_now_add'] = True
        if self.auto_now or self.auto_now_add:
            del kwargs['editable']
            del kwargs['blank']
        return name, path, args, kwargs 
Example #27
Source File: __init__.py    From python2017 with MIT License 5 votes vote down vote up
def get_internal_type(self):
        return "DateField" 
Example #28
Source File: __init__.py    From python2017 with MIT License 5 votes vote down vote up
def pre_save(self, model_instance, add):
        if self.auto_now or (self.auto_now_add and add):
            value = datetime.date.today()
            setattr(model_instance, self.attname, value)
            return value
        else:
            return super(DateField, self).pre_save(model_instance, add) 
Example #29
Source File: __init__.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def deconstruct(self):
        name, path, args, kwargs = super(DateField, self).deconstruct()
        if self.auto_now:
            kwargs['auto_now'] = True
        if self.auto_now_add:
            kwargs['auto_now_add'] = True
        if self.auto_now or self.auto_now_add:
            del kwargs['editable']
            del kwargs['blank']
        return name, path, args, kwargs 
Example #30
Source File: __init__.py    From python2017 with MIT License 5 votes vote down vote up
def contribute_to_class(self, cls, name, **kwargs):
        super(DateField, self).contribute_to_class(cls, name, **kwargs)
        if not self.null:
            setattr(
                cls, 'get_next_by_%s' % self.name,
                curry(cls._get_next_or_previous_by_FIELD, field=self, is_next=True)
            )
            setattr(
                cls, 'get_previous_by_%s' % self.name,
                curry(cls._get_next_or_previous_by_FIELD, field=self, is_next=False)
            )