I was looking for a way to save screen real estate, by using icons instead of labels for my list of choices, which in addition should be displayed as horizontal radio buttons. For example, I wanted to use thumbs_up.gif instead of "approve". I found a HorizontalRadioRenderer here:
Thanks to Barry McClendon for this snippet!
At first, I tried to achieve display of icons instead of labels by modifying the render method, but after a while I gave up on that and decided to just use the choices tuple. This doesn't work too well with a select box (no icons, no text), but in combination with a radio widget it looks quite nice. If you mark the strings for translation, you can also easily change icons, alt and title for each language.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | # -*- coding: utf-8 -*-
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe
from django.conf import settings
APPROVAL_CHOICES = (
(1, mark_safe(_('<img src="%(media_url)simg/thumbs_up.gif" alt="approve" title="approve">' %
{'media_url': settings.MEDIA_URL, },
))),
(2, mark_safe(_('<img src="%(media_url)simg/thumbs_down.gif" alt="disapprove" title="disapprove">' %
{'media_url': settings.MEDIA_URL, },
))),
(0, mark_safe(_('<img src="%(media_url)simg/question_mark.gif" alt="undecided" title="undecided">' %
{'media_url': settings.MEDIA_URL, },
))),
)
class HorizontalRadioRenderer(forms.RadioSelect.renderer):
"""renders horizontal radio buttons.
found here:
https://wikis.utexas.edu/display/~bm6432/Django-Modifying+RadioSelect+Widget+to+have+horizontal+buttons
"""
def render(self):
return mark_safe(u'\n'.join([u'%s\n' % w for w in self]))
class ApprovalForm(forms.Form):
approval = forms.ChoiceField(choices=APPROVAL_CHOICES,
initial=0,
widget=forms.RadioSelect(renderer=HorizontalRadioRenderer),
)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Nice, but what happen if the icon's are in database? Thanks
#
You can have a betters solution if you DRY: Don't repeat yourself. There are three times "<img ... alt... title...>". I would not put any markup into the choices. The html should be created in render().
#
Please login first before commenting.