Login

Custom Widget Types for HTML5 Form Fields

Author:
leveillej
Posted:
May 18, 2010
Language:
Python
Version:
1.2
Tags:
forms widget html5
Score:
4 (after 4 ratings)

I recently needed an easy way to add different input types to form fields based on the type of input. So, I created a widgets.py file and added varying input classes to meet my needs.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from django.forms.widgets import TextInput, DateInput, DateTimeInput, TimeInput

class MyEmailInput(TextInput):
    input_type = 'email'

class MyNumberInput(TextInput):
    input_type = 'number'

class MyTelephoneInput(TextInput):
    input_type = 'tel'

class MyDateInput(DateInput):
    input_type = 'date'

class MyDateTimeInput(DateTimeInput):
    input_type = 'datetime'

class MyTimeInput(TimeInput):
    input_type = 'time'

...
from django.contrib.localflavor.us.forms import USPhoneNumberField
from my.contrib.forms.widgets import *

class MyModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)
        self.fields['return_date'].widget = MyDateInput(attrs={'class':'date'})
        self.fields['passenger_count'].widget = MyNumberInput(attrs={'min':0})
        self.fields['email'].widget = MyEmailInput()

    phone = USPhoneNumberField(
        required=False,
        help_text=u'Phone numbers must be in XXX-XXX-XXXX format',
        label=u'Phone Number',
        widget=MyTelephoneInput()
    )

More like this

  1. Django Number Input by silent1mezzo 4 years, 1 month ago
  2. Custom admin widgets by field type by dgouldin 6 years ago
  3. Autocomplete TextInput Widget w/ Static Data (jQuery UI) by JoeLinux 2 years ago
  4. Dynamically change a form select widget to a hidden widget by epicserve 5 years, 9 months ago
  5. Math Captcha Field and Widget by btaylordesign 3 years, 6 months ago

Comments

Please login first before commenting.