hey guys, i want to create a widget that renders a phone field in the following format
box - box2 - box3
i have tried the different code snippets provided in this same site, however they dont overide the html rendering, which is what i want to do
for example this:
class USPhoneNumberMultiWidget(forms.MultiWidget):
"""
A Widget that splits US Phone number input into three <input type='text'> boxes.
"""
def __init__(self,attrs=None):
widgets = (
forms.TextInput(attrs={'size开发者_高级运维':'3','maxlength':'3', 'class':'phone'}),
forms.TextInput(attrs={'size':'3','maxlength':'3', 'class':'phone'}),
forms.TextInput(attrs={'size':'4','maxlength':'4', 'class':'phone'}),
)
super(USPhoneNumberMultiWidget, self).__init__(widgets, attrs)
def decompress(self, value):
if value:
return value.split('-')
return (None,None,None)
def value_from_datadict(self, data, files, name):
value = [u'',u'',u'']
# look for keys like name_1, get the index from the end
# and make a new list for the string replacement values
for d in filter(lambda x: x.startswith(name), data):
index = int(d[len(name)+1:])
value[index] = data[d]
if value[0] == value[1] == value[2] == u'':
return None
return u'%s-%s-%s' % tuple(value)
renders an html input of:
box|box2|box3
so how can i overwrite the rendering so that it renders:
box - box2 - box3
i would also appreciate any documentation that explains how to create custom widgets, so far i haven't found any
models.py:
class Preference(models.Model):
phone = models.PositiveIntegerField(blank=True)
class PreferenceForm(ModelForm):
class Meta:
model = Preference
widgets = {
'phone':USPhoneNumberMultiWidget(attrs={'class':'firstnumberbox', 'id':'firstcellphone', 'name':'firstphone'}),
Html rendered:
<dt><label for="firstcellphone"> Cell Phone:</label></dt>
<dd class="phones"><input name="firstphone" id="firstcellphone_0" maxlength="3" type="text" class="firstnumberbox" size="3" /> - <input name="firstphone" id="firstcellphone_1" maxlength="3" type="text" class="firstnumberbox" size="3" /> - <input name="firstphone" id="firstcellphone_2" maxlength="4" type="text" class="firstnumberbox" size="4" /></dd>
You can override the MultiWidget's format_output method:
def format_output(self, rendered_widgets):
return u'%s - %s - %s' % \
(rendered_widgets[0], rendered_widgets[1], rendered_widgets[2])
There isn't a ton of documentation on custom form widgets. I've only made a couple, and they took a lot of tinkering. Hope that helps!
精彩评论