django.forms DateField Python Code Examples

The DateField (documentation) class in the django.forms module in the Django web framework provides a mechanism for safely handling dates, but not times, as input from an HTTP POST request. The request is typically generated by an HTML form created from a Django web application.

Example 1 from django-filter

django-filter (project documentation and PyPI page) makes it easier to filter down querysets from the Django ORM by providing common bits of boilerplate code. django-filter is provided as open source.

django-filter / django_filters / fields.py

from collections import namedtuple
from datetime import datetime, time

from django import forms
from django.utils.dateparse import parse_datetime
from django.utils.encoding import force_str
from django.utils.translation import gettext_lazy as _

from .conf import settings
from .constants import EMPTY_VALUES
from .utils import handle_timezone
from .widgets import (
    BaseCSVWidget,
    CSVWidget,
    DateRangeWidget,
    LookupChoiceWidget,
    RangeWidget
)


class RangeField(forms.MultiValueField):
    widget = RangeWidget

    def __init__(self, fields=None, *args, **kwargs):
        if fields is None:
            fields = (
                forms.DecimalField(),
                forms.DecimalField())
        super().__init__(fields, *args, **kwargs)

    def compress(self, data_list):
        if data_list:
            return slice(*data_list)
        return None


class DateRangeField(RangeField):
    widget = DateRangeWidget

    def __init__(self, *args, **kwargs):
        fields = (
            forms.DateField(),
            forms.DateField())
        super().__init__(fields, *args, **kwargs)

    def compress(self, data_list):
        if data_list:
            start_date, stop_date = data_list
            if start_date:
                start_date = handle_timezone(
                    datetime.combine(start_date, time.min),
                    False
                )
            if stop_date:
                stop_date = handle_timezone(
                    datetime.combine(stop_date, time.max),
                    False
                )
            return slice(start_date, stop_date)
        return None


## ... source file continues with no further DateField examples ...

Example 2 from django-floppyforms

django-floppyforms (project documentation and PyPI page) is a Django code library for better control over rendering HTML forms in your templates.

The django-floppyforms code is provided as open source and maintained by the collaborative developer community group Jazzband.

django-floppyforms / floppyforms / fields.py

import django
from django import forms
import decimal

from .widgets import (TextInput, HiddenInput, CheckboxInput, Select,
                      ClearableFileInput, SelectMultiple, DateInput,
                      DateTimeInput, TimeInput, URLInput, NumberInput,
                      EmailInput, NullBooleanSelect, SlugInput, IPAddressInput,
                      SplitDateTimeWidget, SplitHiddenDateTimeWidget,
                      MultipleHiddenInput)

__all__ = (
    'Field', 'CharField', 'IntegerField', 'DateField', 'TimeField',
    'DateTimeField', 'EmailField', 'FileField', 'ImageField', 'URLField',
    'BooleanField', 'NullBooleanField', 'ChoiceField', 'MultipleChoiceField',
    'FloatField', 'DecimalField', 'SlugField', 'RegexField',
    'GenericIPAddressField', 'TypedChoiceField', 'FilePathField',
    'TypedMultipleChoiceField', 'ComboField', 'MultiValueField',
    'SplitDateTimeField',
)
if django.VERSION < (1, 9):
    __all__ += ('IPAddressField',)


class Field(forms.Field):
    widget = TextInput
    hidden_widget = HiddenInput


class CharField(Field, forms.CharField):
    widget = TextInput

    def widget_attrs(self, widget):
        attrs = super(CharField, self).widget_attrs(widget)
        if attrs is None:
            attrs = {}
        if self.max_length is not None and isinstance(widget, (TextInput, HiddenInput)):
            # The HTML attribute is maxlength, not max_length.
            attrs.update({'maxlength': str(self.max_length)})
        return attrs


class BooleanField(Field, forms.BooleanField):
    widget = CheckboxInput


class NullBooleanField(Field, forms.NullBooleanField):
    widget = NullBooleanSelect


class ChoiceField(Field, forms.ChoiceField):
    widget = Select


class TypedChoiceField(ChoiceField, forms.TypedChoiceField):
    widget = Select


class FilePathField(ChoiceField, forms.FilePathField):
    widget = Select


class FileField(Field, forms.FileField):
    widget = ClearableFileInput


class ImageField(Field, forms.ImageField):
    widget = ClearableFileInput


class MultipleChoiceField(Field, forms.MultipleChoiceField):
    widget = SelectMultiple
    hidden_widget = MultipleHiddenInput


class TypedMultipleChoiceField(MultipleChoiceField,
                               forms.TypedMultipleChoiceField):
    pass


class DateField(Field, forms.DateField):
    widget = DateInput


## ... source file continues with no further DateField examples ...

Example 3 from django-jet

django-jet (project documentation, PyPI project page and more information) is a fancy Django Admin panel replacement.

The django-jet project is open source under the GNU Affero General Public License v3.0.

django-jet / jet / filters.py

from django.contrib.admin import RelatedFieldListFilter
from django.utils.encoding import smart_text
from django.utils.html import format_html
try:
    from django.core.urlresolvers import reverse
except ImportError: # Django 1.11
    from django.urls import reverse

try:
    from django.contrib.admin.utils import get_model_from_relation
except ImportError: # Django 1.6
    from django.contrib.admin.util import get_model_from_relation

try:
    from django.forms.utils import flatatt
except ImportError: # Django 1.6
    from django.forms.util import flatatt


class RelatedFieldAjaxListFilter(RelatedFieldListFilter):
    template = 'jet/related_field_ajax_list_filter.html'
    ajax_attrs = None

    def has_output(self):
        return True

    def field_choices(self, field, request, model_admin):
        model = field.remote_field.model if hasattr(field, 'remote_field') else field.related_field.model
        app_label = model._meta.app_label
        model_name = model._meta.object_name

        self.ajax_attrs = format_html('{0}', flatatt({
            'data-app-label': app_label,
            'data-model': model_name,
            'data-ajax--url': reverse('jet:model_lookup'),
            'data-queryset--lookup': self.lookup_kwarg
        }))

        if self.lookup_val is None:
            return []

        other_model = get_model_from_relation(field)
        if hasattr(field, 'rel'):
            rel_name = field.rel.get_related_field().name
        else:
            rel_name = other_model._meta.pk.name

        queryset = model._default_manager.filter(**{rel_name: self.lookup_val}).all()
        return [(x._get_pk_val(), smart_text(x)) for x in queryset]


try:
    from collections import OrderedDict
    from django import forms
    from django.contrib.admin.widgets import AdminDateWidget
    from rangefilter.filter import DateRangeFilter as OriginalDateRangeFilter
    from django.utils.translation import ugettext as _


    class DateRangeFilter(OriginalDateRangeFilter):
        def get_template(self):
            return 'rangefilter/date_filter.html'

        def _get_form_fields(self):
            # this is here, because in parent DateRangeFilter AdminDateWidget
            # could be imported from django-suit
            return OrderedDict((
                (self.lookup_kwarg_gte, forms.DateField(
                    label='',
                    widget=AdminDateWidget(attrs={'placeholder': _('From date')}),
                    localize=True,
                    required=False
                )),
                (self.lookup_kwarg_lte, forms.DateField(
                    label='',
                    widget=AdminDateWidget(attrs={'placeholder': _('To date')}),
                    localize=True,
                    required=False
                )),
            ))

        @staticmethod
        def _get_media():
            css = [
                'style.css',
            ]
            return forms.Media(
                css={'all': ['range_filter/css/%s' % path for path in css]}
            )
except ImportError:
    pass

Example 4 from register

register is a Django, Bootstrap, PostgreSQL project that is open source under the GNU General Public License v3.0. This web application makes it easier for people to register as organ donors. You can see the application live at https://register.organize.org/.

register / registration / forms.py

from __future__ import unicode_literals

import logging
import re
import collections
import datetime

import django.forms
import django.forms.utils
import django.forms.widgets
import django.core.validators
import django.core.exceptions
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe

import form_utils.forms
import requests
import dateutil.parser
import validate_email

logger = logging.getLogger(__name__)


## ... source file abbreviated to get to the DateField example ...

def register_form_generator(conf):
    fieldsets = []
    fields = collections.OrderedDict()
    for index, fieldset_def in enumerate(conf['fieldsets']):
        fieldset_title = _(fieldset_def['title'])
        fieldset_fields = fieldset_def['fields']

        if not fieldset_fields:
            continue
        fieldset = (unicode(index), {'legend': fieldset_title, 'fields': []}, )

        has_booleans = False

        for field_def in fieldset_def['fields']:
            field_name = field_def['field_name']
            field_type = field_def.get('type')
            label = _(field_def['human_name']) or ''

            is_required = field_def.get('required', False)
            max_length = field_def.get('length')
            initial = field_def.get('default')
            if field_def.get('help_text'):
                help_text = _(field_def.get('help_text'))
            else:
                help_text = ''
            # process choices to add internationalization
            choices = field_def.get('choices')
            if choices:
                choices = [(a, _(b)) for a, b in choices]
            is_editable = field_def.get('editable', True)
            min_value = field_def.get('min_value')

            d = {
                'label': label,
            }

            if field_type == 'string':
                d['required'] = is_required
                d['initial'] = initial
                if choices and is_editable:
                    d['help_text'] = help_text
                    d['choices'] = choices
                    d['widget'] = django.forms.RadioSelect
                    field_class = django.forms.ChoiceField
                elif field_name == 'email':
                    d['max_length'] = max_length
                    d['help_text'] = help_text
                    field_class = django.forms.EmailField
                elif field_name == 'license_id' \
                        and 'license_id_formats' in conf:
                    d['max_length'] = max_length
                    license_id_formats = '{}{}{}'.format(
                            _('<p class=\'hint-license-id-format\'>Valid state License IDs should look like: '),
                            ', '.join(map(unicode, conf['license_id_formats'])), '</p>')
                    help_text = '{}{}{}'.format('<p> ', unicode(help_text), '</p>')
                    license_id_formats = '{}{}'.format(license_id_formats, help_text)
                    d['help_text'] = mark_safe(license_id_formats)
                    field_class = django.forms.CharField
                else:
                    d['max_length'] = max_length
                    d['help_text'] = help_text
                    field_class = django.forms.CharField
            elif field_type == 'date':
                d['required'] = is_required
                d['initial'] = initial
                d['help_text'] = help_text
                if min_value:
                    d['validators'] = [validate_date_generator(min_value), ]
                field_class = django.forms.DateField
            elif field_type == 'boolean':
                has_booleans = True
                d['initial'] = initial
                # this must be false otherwise checkbox must be checked
                if field_name == 'agree_to_tos':
                    d['help_text'] = mark_safe(help_text)
                    d['label'] = mark_safe(label)
                else:
                    d['required'] = False
                    d['help_text'] = help_text
                field_class = django.forms.BooleanField
            else:
                raise Exception('Unknown field type: {}'.format(field_type))

            fields[field_name] = field_class(**d)
            fieldset[1]['fields'].append(field_name)

            widget = fields[field_name].widget
            if not is_editable:
                if isinstance(widget, django.forms.Select):
                    widget.attrs['disabled'] = 'disabled'
                else:
                    widget.attrs['readonly'] = 'readonly'
            if field_type == 'date':
                widget.attrs['placeholder'] = '__/__/____'
                widget.attrs['class'] = 'date'
            if field_name == 'phone_number':
                widget.attrs['placeholder'] = '(___) ___-____'
                widget.attrs['class'] = 'phonenumber'
            if field_name == 'ssn':
                widget.attrs['placeholder'] = '____'
                widget.attrs['class'] = 'ssn'

        if has_booleans:
            fieldset[1]['classes'] = ['checkboxes', ]
        fieldsets.append(fieldset)

    cls_name = 'RegisterForm{}'.format(
        RE_NON_ALPHA.sub('', conf['title'].title())).encode(
        'ascii', errors='ignore')

    cls = type(
        cls_name,
        (form_utils.forms.BetterBaseForm, django.forms.BaseForm, ), {
            'base_fieldsets': fieldsets,
            'base_fields': fields,
            'base_row_attrs': {},
            'clean': register_form_clean,
            'clean_birthdate': register_form_clean_birthdate,
            'clean_phone_number': register_form_clean_phone_number,
            'clean_ssn': register_form_clean_ssn,
            'clean_license_id': register_form_clean_license_id,
            'api_errors': {},
            'skip_api_error_validation': False,
            'validate_organ_tissue_selection': conf.get('validate_organ_tissue_selection', None),
        })
    return cls


class RevokeForm(django.forms.Form):
    email = django.forms.EmailField(label=_('Email'))
    first_name = django.forms.CharField(
        label=_('First Name'), max_length=150, min_length=1)
    middle_name = django.forms.CharField(
        label=_('Middle Name'), max_length=150, min_length=0, required=False)
    last_name = django.forms.CharField(
        label=_('Last Name'), max_length=150, min_length=1)
    postal_code = django.forms.CharField(
        label=_('Postal Code'),
        max_length=5, min_length=5, validators=[validate_postal_code])
    gender = django.forms.ChoiceField(
        label=_('Gender'), choices=CHOICES_GENDER,
        widget=django.forms.RadioSelect)
    birthdate = django.forms.DateField(
        label=_('Birthdate'),
        widget=django.forms.DateInput(
            attrs={'placeholder': '__/__/____', 'class': 'date',}))
    # agree_to_tos = django.forms.BooleanField(
    #     label=mark_safe(_('In order to revoke my organ and tissue donation status through Organize, I agree to ORGANIZE\'s '
    #                       '<a href="#" onClick="window.open(\'/terms-of-service/\', \'_blank\', \'width=900,height=900\')'
    #                       '">Terms of Service</a> and <a href="#" onClick="window.open(\'/privacy-policy/\', \'_blank\', '
    #                       '\'width=900,height=900\')">Privacy Policy</a>.')),
    #     widget=django.forms.widgets.CheckboxInput(
    #         attrs={'required': 'required', }))
    agree_to_tos = django.forms.BooleanField(label='', widget=django.forms.widgets.CheckboxInput(attrs={'required': 'required', }))

    def clean_email(self):
        email = self.cleaned_data['email']
        if settings.DISABLE_EMAIL_VALIDATION:
            logger.warning(
                'Email validation disabled: DISABLE_EMAIL_VALIDATION is set')
            return email
        # use mailgun email address validator to check this email
        if not hasattr(settings, 'MAILGUN_PUBLIC_API_KEY'):
            logger.warning(
                'Cannot validate email: MAILGUN_PUBLIC_API_KEY not set')
            return email
        r = requests.get(
            'https://api.mailgun.net/v2/address/validate',
            data={'address': email, },
            auth=('api', settings.MAILGUN_PUBLIC_API_KEY))
        if r.status_code == 200:
            if r.json()['is_valid']:
                return email
        logger.warning('Cannot validate email: {}'.format(r.text))
        raise django.forms.ValidationError(_('Enter a valid email.'))

## ... source file continues with no further DateField examples ...
1. Introduction 2. Development Environments 3. Data 4. Web Development 5. Deployment 6. DevOps Changelog What Full Stack Means About the Author Future Directions Page Statuses Django ExtensionsDjango Example Codedjango.apps.config AppConfigdjango.conf settingsdjango.conf.urls.urldjango.contrib.admindjango.contrib.admin.filters SimpleListFilterdjango.contrib.admin.sites registerdjango.contrib.auth.decorators login_requireddjango.contrib.auth get_user_modeldjango.contrib.auth.hashers make_passworddjango.core.exceptions ImproperlyConfigureddjango.core.mail.messages EmailMessagedjango.core.mail.send_maildjango.core.management.base BaseCommanddjango.db.models AutoFielddjango.db.models BooleanFielddjango.db.models CharFielddjango.db.models DateFielddjango.db.models DateTimeFielddjango.db.models FileFielddjango.db.models ForeignKeydjango.db.models GenericIPAddressFielddjango.db.models ImageFielddjango.db.models IntegerFielddjango.db.models Modeldjango.db.models PositiveIntegerFielddjango.db.models PositiveSmallIntegerFielddjango.db.models.signaldjango.db.models SlugFielddjango.db.models SmallIntegerFielddjango.db.models TextFielddjango.db OperationalErrordjango.dispatch Signaldjango.formsdjango.forms BooleanFielddjango.forms CharFielddjango.forms ChoiceFielddjango.forms DateFielddjango.forms DateTimeFielddjango.forms EmailFielddjango.forms IntegerFielddjango.forms TypedChoiceFielddjango.http Http404django.http HttpResponsedjango.http HttpResponseBadRequestdjango.http HttpResponseForbiddendjango.http HttpResponseNotModifieddjango.http HttpResponsePermanentRedirectdjango.http HttpResponseRedirectdjango.template.response SimpleTemplateResponsedjango.template.response TemplateResponsedjango.urls.pathdjango.urls reverse_lazydjango.urls.exceptions NoReverseMatchdjango.urls.exceptions Resolver404django.utils.html format_htmldjango.utils.timezone ...or view the full table of contents.

Full Stack Python

Full Stack Python is an open book that explains concepts in plain language and provides helpful resources for those topics.
Updates via Twitter & Facebook.

Matt Makai 2012-2020