Login

Custom Widget Types for HTML5 Form Fields

Author:
leveillej
Posted:
May 18, 2010
Language:
Python
Version:
1.2
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.