问题描述
|
大家好,我想创建一个小部件,以以下格式呈现电话字段
Box - Box2 - Box3
我已经尝试过在同一站点中提供的不同代码段,但是它们不覆盖html渲染,这是我想做的
例如:
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\',forms.TextInput(attrs={\'size\':\'4\',\'maxlength\':\'4\',)
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)
呈现以下内容的html输入:
Box|Box2|Box3
所以我怎么能覆盖渲染以便渲染:
Box - Box2 - Box3
我还要感谢任何解释如何创建自定义小部件的文档,到目前为止,我还没有找到任何文档
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:
<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>
解决方法
您可以覆盖MultiWidget的format_output方法:
def format_output(self,rendered_widgets):
return u\'%s - %s - %s\' % \\
(rendered_widgets[0],rendered_widgets[1],rendered_widgets[2])
自定义表单小部件上没有大量文档。我只结了两对,他们花了很多功夫。希望有帮助!