1

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. enter image description here

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.

Thanks

UPDATE:

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)

and I've added the CSS to my stylesheet:

#radio{
   width: 100px;
   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?

Community
  • 1
  • 1
Daniel Rosenthal
  • 1,386
  • 4
  • 15
  • 32
  • 1
    It's most likely just collapsing due to the table cell. You should look at the HTML and figure out what's going on. You are guessing too many things here.. is the renderer working? If yes, then what's left? – Yuji 'Tomita' Tomita Jul 27 '13 at 01:41
  • @Yuji'Tomita'Tomita Doesn't seem like it's the table cell... I just rendered it on its own, and it's doing the same thing. The renderer is "working" (by which I mean, if I change the renderer, its affect is applied), but doesn't seem to be doing what I want it to. Would more information help? If so, what? – Daniel Rosenthal Jul 29 '13 at 14:44

1 Answers1

1

Whoa: okay.

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.

The renderer now reads as follows:

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)

This makes the radio boxes in an un-ordered list, surrounded by a div with an id of radio.

I then have the css:

#radio ul li label{
    display:inline;
}

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.

Daniel Rosenthal
  • 1,386
  • 4
  • 15
  • 32