django RadioSelect widget list id

末鹿安然 提交于 2021-01-29 04:34:32

问题


I currently have a RadioSelect widget on one of my form classes that I want to style with css. However the rendered widget is contained in an ul and the list has no id.

What is the easiest way to add an id to the rendered list?


回答1:


Subclass RadioFieldRenderer and override render method.

RadioFieldRenderer is an object used by RadioSelect to enable customization of radio widgets.

Example implementation that adds class to ul element:

from django.utils.encoding import force_unicode
from django.utils.safestring import mark_safe

class MyRadioFieldRenderer(forms.widgets.RadioFieldRenderer):

    def render(self):
        """Outputs a <ul> for this set of radio fields."""
        return mark_safe(u'<ul class="inputs-list">\n%s\n</ul>' % 
                u'\n'.join([u'<li>%s</li>'
                % force_unicode(w) for w in self]))

Usage:

field = forms.ChoiceField(label=_('field'),
        choices=FIELD_CHOICES,
        widget=forms.widgets.RadioSelect(
            renderer=MyRadioFieldRenderer
            )
        )



回答2:


I have no solution to modify rendered html. But you can put rendered html inside a tag with id (or a class in my case):

<td class="tria_tag"   >                
                    <ul>
<li><label for="id_935591-estat_0"><input checked="checked" name="935591-estat" value="2" id="id_935591-estat_0" type="radio" class="presenciaEstat" /> Present</label></li>
<li><label for="id_935591-estat_1"><input value="3" type="radio" class="presenciaEstat" name="935591-estat" id="id_935591-estat_1" /> Falta</label></li>
<li><label for="id_935591-estat_2"><input value="4" type="radio" class="presenciaEstat" name="935591-estat" id="id_935591-estat_2" /> Justificada</label></li>
<li><label for="id_935591-estat_3"><input value="5" type="radio" class="presenciaEstat" name="935591-estat" id="id_935591-estat_3" /> Retràs</label></li>
</ul>
                </td>

and then with jquery you can access to :

$('.tria_tag').each(
   function(index) {
     ul=$(this).children().first();
     ...


来源:https://stackoverflow.com/questions/7626878/django-radioselect-widget-list-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!