如何让RadioSelect将图像作为无线电值?

Mar*_*ruz 2 django django-forms

我有以下表格:

class ReviewForm(forms.ModelForm):
class Meta:
    model = Review

    widgets = {
        'tipo' : forms.RadioSelect(),
    }
Run Code Online (Sandbox Code Playgroud)

但我想使用图像作为我的单选按钮的值,图像会根据选项而有所不同,如下所示:

<input type="radio" id="id_tipo_0" value="UP" name="tipo" /><img src="/images/thumb_up.gif"/>
<input type="radio" id="id_tipo_1" value="DOWN" name="tipo" /><img src="/images/thumb_DOWN.gif"/>
Run Code Online (Sandbox Code Playgroud)

我没有关于如何实现这一目标的线索.

Wou*_*ink 9

这个问题有一个很好的解决方案!

ModelChoiceField有方法label_from_instance(self, obj).为ModelChoiceField中的每个选项调用此方法.

您可以使用以下内容覆盖ModelChoiceField.label_from_instance:

def label_from_instance(obj):
    """
    Shows an image with the label
    """
    image = conditional_escape(obj.thumbnail_image.url)
    title = conditional_escape(obj.title)

    label = """<img src="%s" />%s""" % (image, title)

    return mark_safe(label)
Run Code Online (Sandbox Code Playgroud)

注意:您需要使用mark_safe,否则渲染器将转义img标记.应用于conditional_escape用户输入值(标题和URL).

如果您想使用常规,ChoiceField您只需将HTML添加到choices参数并添加即可mark_safe.