Show HTML in Labels for Model Choice Fields

99 views
Skip to first unread message

Adi

unread,
Dec 30, 2010, 7:36:01 PM12/30/10
to Django users
Hi I have a situation like this

class AppearanceThemesForm(forms.Form):
page_theme =
forms.ModelChoiceField(widget=forms.RadioSelect(attrs={'title':'Select
the appropriate theme for your pages.'}),

queryset=Theme.objects.filter(section="1"),

initial=Theme.objects.get(section="1",representation="").pk,
label="Page Theme")

And my Theme model is like this:

class Theme(models.Model):
name = models.CharField(max_length=32)
image = models.ImageField(upload_to="images/themes", null=True)

def __unicode__(self):
return "%s" % (self.name)


When I render AppearanceThemesForm in my template, i would like to be
able to show a link next to the label. If a user clicks the link, the
webpage displays the image associated with Theme.

I tried putting in a custom field that extends the ModelChoiceField,
and in the label_from_instance method, tried to output the HTML, but
that gets escaped.

What is the proper way to achieve what i am trying to do?

Alternatively, how do i get access the underlying model object behind
the modelchoice field in my templates?

Adi

unread,
Jan 3, 2011, 12:34:19 AM1/3/11
to Django users
I was able to find the solution to it myself.

The key was to
1. Create a custom field that extended ModelChoiceField.
2. Overwrite the label_from_instance method in the custom field.
3. Return a HTML string from the label_from_instance method, and
marking that as a safe_string.


from django.forms import ModelChoiceField
from django.utils.safestring import mark_safe

class ThemeChoiceField(ModelChoiceField):
def label_from_instance(self,obj):
return mark_safe("%s - Click <a target='_other' rel='#theme_
%s' class='overlay_trigger'>here</a> to see an example. \
<div class='simple_overlay' id='theme_%s'><img src='%s'></
img></div> " \
% (obj.name, obj.pk, obj.pk, obj.image.url))

-Adi
Reply all
Reply to author
Forward
0 new messages