自定义RadioSelect渲染 [英] Custom RadioSelect Rendering
问题描述
我正在尝试使Django的RadioSelect小部件水平呈现.我发现以下SO帖子,以为已解决了该问题:对齐单选按钮基本上以django形式水平放置,基本上规定要使用自定义渲染器,如下所示:
I'm trying to make Django's RadioSelect widget render horizontally. I found the following SO post, that I thought had solved the problem: Align radio buttons horizontally in django forms, it basically states to use a custom Renderer, as follows:
class HorizontalRadioRenderer(forms.RadioSelect.renderer):
def render(self):
return mark_safe(u'\n'.join([u'%s\n' % w for w in self]))
class MyForm(ModelForm):
select=forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect(renderer=HorizontalRadioRenderer
但是当我实现它时,我仍然可以使单选按钮垂直显示.这是屏幕截图.
But when I implement this, I still get the radio selection buttons rendering vertically. Here's a screenshot.
对于我的表格,这是一个严重的问题.知道为什么它不能正常工作吗?如果很重要,则将表格呈现在表格中.
This is a seriois problem for my form. Any idea why it isn't working correctly? If it matters, the form is being rendered in a table.
谢谢
更新:
好的,我尝试了其他方法.现在,渲染器为:
Ok, I've tried something else. The renderer is now:
def render(self):
internal=''.join(['<span id="radio">%s</span>' % w for w in self])
return mark_safe(u'%s' %internal)
并且我已经将CSS添加到样式表中:
and I've added the CSS to my stylesheet:
#radio{
width: 100px;
float: left;
}
这使RadioBoxes内联,并且外观很棒.但是现在有一个更大的问题.从上面的屏幕快照中可以看到,我有2个选择,是和不适用.现在,如果我单击是"或不适用",则会选择不适用".我认为这可能是因为它们都在具有相同ID的范围内,但是如果我将其更改为class="radio"
,则会发生相同的情况.如果我从CSS中删除float: left
,则它可以正常工作(但是,当然不会水平显示).知道是什么原因造成的吗?
This renders the RadioBoxes inline, and looks great. But now there's an even bigger problem. As seen in my screenshot above, I have 2 choices, Yes and N/A. Right now, if I click on either yes or N/A, N/A gets selected. I thought this might be because they were both in spans with the same id, but if I change it to class="radio"
the same thing happens. If I remove float: left
from the CSS, then it works normally (but, of course, isn't displayed horizontally). Any idea what's causing this?
推荐答案
哇!好的.
仍然不确定为什么使用具有相同ID或类的它们会导致它们的行为与同一广播框相同,但是我想出了一个解决方案.
Still not sure why having them with the same id or class caused them to behave as the same radio box, but I've come up with a solution.
渲染器现在显示如下:
def render(self):
internal = ''.join(['<li>%s</li>' % w for w in self])
return mark_safe(u'<div id="radio"><ul>%s</ul></div>' %internal)
这会使单选框处于无序列表中,并被一个带单选ID的div包围.
This makes the radio boxes in an un-ordered list, surrounded by a div with an id of radio.
然后我得到了css:
#radio ul li label{
display:inline;
}
这使它们排成一行.好,易于.当听起来像是对另一个SO用户这样做时,不知道为什么其他方法不起作用.
This puts them in a line. Nice and easy. Don't know why the other approach didn't work, when it sounded like it did for another SO user.
这篇关于自定义RadioSelect渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!