3

I have option groups, somethings like this:

Choices = (('Group1',(('Option1','Option1'),('Option2','Option2'))))

Is there anyway to display the options horizontally instead of vertically using the SelectMultiple Widget? My problem is that I have too many Groups, so if i could have something like the following it would be better.

Group 1 - Option1, Option2, ...
Group 2 - Option1, Option2, ...

Update - Found this but it only "works" for CheckboxSelectMultiple. How should I change it in order to work with SelectMultiple?

from django.utils.safestring import mark_safe

class HorizWidget(forms.SelectMultiple):

    def render(self, *args, **kwargs):
        output = super(HorizWidget, self).render(*args,**kwargs) 
        return mark_safe(output.replace(u'<ul>', u'').replace(u'</ul>', u'').replace(u'<li>', u'<p>').replace(u'</li>', u'</p>'))
gypaetus
  • 6,873
  • 3
  • 35
  • 45
Pedro
  • 85
  • 2
  • 7

2 Answers2

2

Are you using the Django admin? If so, the filter_horizontal and filter_vertical options can make multiple selects much more usable (I must admit, I haven't tried them before with grouped choices).

If that doesn't help, then you can subclass the SelectMultiple widget and override the render methods as you wish. I personally prefer to use javascript widget plugins where possible (e.g. jquery-ui-multiselect). They can often work with just a few lines of javascript in your template header, which I find a lot less painful than writing custom widget html.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • Yes, I'm using Django Admin. Guess I will try overwriting the SelectMultiple widget. I'm still very new to Django... – Pedro Mar 06 '12 at 10:08
  • Found this but it only "works" for CheckboxSelectMultiple. How should I change it in order to work with SelectMultiple? `class HorizWidget(forms.SelectMultiple): def render(self, *args, **kwargs): output = super(HorizWidget, self).render(*args,**kwargs) return mark_safe(output.replace(u'
      ', u'').replace(u'
    ', u'').replace(u'
  • ', u'

    ').replace(u'

  • ', u''))` – Pedro Mar 06 '12 at 10:25
  • 1
    Please don't post large code blocks in the comments -- you lose all the indentation so it's very hard to read. You can edit your original question to include the code there. Sorry, but I'm not able to help you write your custom widget, I hope that somebody can help you or you can work it out. Good luck! – Alasdair Mar 06 '12 at 10:33