我想将jquery ui buttonset用于django形式的radioselect。我正在使用下面的自定义渲染器作为radioselect小部件,但输入落在标签内。 jquery ui不适用于该结构。在渲染器中需要更改什么才能将输入标记放在标签之前?
forms.py:
class SimpleRadioFieldRenderer(forms.widgets.RadioFieldRenderer):
def render(self):
"""Outputs widget without <ul> or <li> tags."""
return mark_safe(u'\n'.join([u'%s'
% force_unicode(w) for w in self]))
class MyForm(Form):
myradiofield = ChoiceField(
widget=RadioSelect(renderer=SimpleRadioFieldRenderer),
required=True,
choices=(('a','one choice'), ('b','another choice')))
以下是django在模板中呈现的方式:
<label for="id_myradiofield_0"><input type="radio" name="myradiofield" value="a" id="id_myradiofield_0"> one choice</label>
<label for="id_myradiofield_1"><input type="radio" name="myradiofield" value="b" id="id_myradiofield_0"> another choice</label>
以下是jquery ui的预期:
<input type="radio" name="myradiofield" value="a" id="id_myradiofield_0"><label for="id_myradiofield_0"> one choice</label>
<input type="radio" name="myradiofield" value="b" id="id_myradiofield_0"> <label for="id_myradiofield_1">another choice</label>
提前感谢您的帮助。
答案 0 :(得分:4)
您可以针对该问题扩展RadioInput
和RadioFieldRenderer
类,并使用MyCustomRenderer
作为渲染器
class MyRadioInput(RadioInput):
def __unicode__(self):
if 'id' in self.attrs:
label_for = ' for="%s_%s"' % (self.attrs['id'], self.index)
else:
label_for = ''
choice_label = conditional_escape(force_unicode(self.choice_label))
return mark_safe(u'<label%s>%s</label>%s' % (label_for, choice_label, self.tag()))
class MyCustomRenderer( RadioFieldRenderer ):
def __iter__(self):
for i, choice in enumerate(self.choices):
yield MyRadioInput(self.name, self.value, self.attrs.copy(), choice, i)
def __getitem__(self, idx):
choice = self.choices[idx] # Let the IndexError propogate
return MyRadioInput(self.name, self.value, self.attrs.copy(), choice, idx)
如果您想要解决方案客户端:
<script>
$("label>input").each(function(index, item){
$(item).insertBefore($(item).parent())
})
</script>
您可以通过修改django.forms.widgets.py
来获得解决方案:
滚动到class RadioInput
我们将修改
的最后一行 def __unicode__(self):
return mark_safe(u'<label%s>%s %s</label>' % (label_for, self.tag(), choice_label)) #OLD
转到
return mark_safe(u'<label%s>%s</label>%s' % (label_for, choice_label, self.tag())) #NEW
答案 1 :(得分:0)
尝试以下方法:
myradiofield = forms.ChoiceField(choices=YOURCHOICES,initial=0,
widget=forms.RadioSelect(renderer=HorizontalRadioRenderer),)