tag (forms)

archive

html5 django form fields Jul
06
1
2

If you're ever developing for mobile it's really handy to use the HTML5 form inputs for things like email and url to bring up the contextual keyboard layouts.

An easy way to create the HTML5 input elements is to extend the Input widget input_type.

from django import forms
from django.widgets import Input


class Html5EmailInput(Input):
    input_type = 'email'


class Html5URLInput(Input):
    input_type = 'url'


class CustomForm(forms.Form):
    email = forms.CharField(widget=Html5EmailInput())
    url = forms.CharField(widget=Html5URLInput())

comments

display the value of a django form field in a template Jul
06
1
2

Sometimes you need to get at the raw value of a field in a django form. This is easily done in 1.3 using the following:

{{ form.field_name.value }}

If you're running a version lower than 1.3 you can get at the value with:

{% if form.instance.field_name %}
{{ form.instance.field_name }}
{% else %}
{{ form.data.field_name }}
{% endif %}

comments

change the default formating of the DateField in django forms Feb
23
1
1

Django forms are great, but sometimes you need to do a little work to get things just the way you want. The DateField has an easy way to restrict how data is entered through the input_formats option; but unless if I'm missing something there's isn't a similar way to help you set how the field displays the date in the template.

The default way the forms.DateField is displayed is YYYY-MM-DD, which is typically not what you want to present to the users.

The easiest way I have found to change how the date field displays is to write a small custom form field that inherits from forms.DateField that overrides the widget.

It would look something like this:

from django import forms
from django.utils.translation import ugettext_lazy as _


class FormattedDateField(forms.DateField):
    widget = forms.DateInput(format='%m/%d/%Y')

    def __init__(self, *args, **kwargs):
        super(FormattedDateField, self).__init__(*args, **kwargs)
        self.input_formats = ('%m/%d/%Y',)


class ProfileForm(forms.Form):
    email = forms.EmailField()
    first_name = forms.CharField(max_length=100)
    last_name = forms.CharField(max_length=100)
    birthday = FormattedDateField()

Or for a short-hand version that doesn't require overriding the form class could look something like the following:

class ProfileForm(forms.Form):
    email = forms.EmailField()
    first_name = forms.CharField(max_length=100)
    last_name = forms.CharField(max_length=100)
    birthday = forms.DateField(widget=forms.DateInput(format='%m/%d/%Y')), input_formats=('%m/%d/%Y',))

Now, when I initialize the birthday field in the form instead of displaying YYYY-MM-DD, it will look like MM/DD/YYYY which is more natural to an American audience.

comments