Python django.forms.DateField() Examples

The following are 30 code examples for showing how to use django.forms.DateField(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.forms , or try the search function .

Example 1
Project: ideascube   Author: ideascube   File: forms.py    License: 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 2
Project: django-admin-rangefilter   Author: silentsokolov   File: filter.py    License: 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 3
Project: urbanfootprint   Author: CalthorpeAnalytics   File: feature_field_mixin.py    License: 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 4
Project: wagtail   Author: wagtail   File: test_edit_handlers.py    License: 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 5
Project: wagtail   Author: wagtail   File: test_edit_handlers.py    License: 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 6
Project: djongo   Author: nesdis   File: tests.py    License: 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 7
Project: djongo   Author: nesdis   File: test_input_formats.py    License: 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 8
Project: djongo   Author: nesdis   File: test_input_formats.py    License: 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 9
Project: djongo   Author: nesdis   File: test_input_formats.py    License: 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 10
Project: djongo   Author: nesdis   File: test_input_formats.py    License: 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
Project: djongo   Author: nesdis   File: test_input_formats.py    License: 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 12
Project: djongo   Author: nesdis   File: test_input_formats.py    License: 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 13
Project: djongo   Author: nesdis   File: test_input_formats.py    License: 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 14
Project: djongo   Author: nesdis   File: test_input_formats.py    License: 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 15
Project: djongo   Author: nesdis   File: test_input_formats.py    License: 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 16
Project: djongo   Author: nesdis   File: tests.py    License: 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 17
Project: djongo   Author: nesdis   File: test_input_formats.py    License: 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 18
Project: djongo   Author: nesdis   File: test_input_formats.py    License: 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 19
Project: django-accounting   Author: dulacp   File: template_tags_tests.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        class MockForm(forms.Form):
            text_field = forms.CharField()
            date_field = forms.DateField()
        self.form_class = MockForm
        self.form = self.form_class() 
Example 20
Project: coursys   Author: sfu-fas   File: other.py    License: GNU General Public License v3.0 5 votes vote down vote up
def make_entry_field(self, fieldsubmission=None):
        c = forms.DateField(required=self.config['required'],
            label=self.config['label'],
            validators=[self._validator],
            help_text=self.config['help_text'])
        
        c.widget.attrs['class'] = 'date-input' # a JS chunk uses the class to turn on the datepicker.
        
        if fieldsubmission:
            c.initial = fieldsubmission.data['info']

        return c 
Example 21
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.0 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 22
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.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 23
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get_internal_type(self):
        return "DateField" 
Example 24
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.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 25
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get_prep_lookup(self, lookup_type, value):
        # For dates lookups, convert the value to an int
        # so the database backend always sees a consistent type.
        if lookup_type in ('month', 'day', 'week_day', 'hour', 'minute', 'second'):
            return int(value)
        return super(DateField, self).get_prep_lookup(lookup_type, value) 
Example 26
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get_prep_value(self, value):
        value = super(DateField, self).get_prep_value(value)
        return self.to_python(value) 
Example 27
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.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 28
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.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 = timezone.now()
            setattr(model_instance, self.attname, value)
            return value
        else:
            return super(DateTimeField, self).pre_save(model_instance, add)

    # contribute_to_class is inherited from DateField, it registers
    # get_next_by_FOO and get_prev_by_FOO

    # get_prep_lookup is inherited from DateField 
Example 29
Project: kobo-predict   Author: awemulya   File: forms.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, project, *args, **kwargs):
        kwargs.setdefault('label_suffix', '')
        super(SiteBulkEditForm, self).__init__(*args, **kwargs)

        self.fields['sites'] = forms.ModelMultipleChoiceField(
            widget=forms.CheckboxSelectMultiple,
            queryset=project.sites.all(),
        )

        for attr in project.site_meta_attributes:
            q_type = attr['question_type']
            q_name = attr['question_name']

            if q_type == 'Number':
                field = forms.FloatField()
            elif q_type == 'Date':
                field = forms.DateField()
            elif q_type == 'MCQ':
                options = attr.get('mcq_options') or []
                choices = [o.get('option_text') for o in options]
                choices = [(c, c) for c in choices]
                field = forms.ChoiceField(choices=choices)
            else:
                field = forms.CharField()

            self.fields[q_name] = field 
Example 30
Project: bioforum   Author: reBiocoder   File: __init__.py    License: MIT License 5 votes vote down vote up
def get_internal_type(self):
        return "DateField"