如何在Django RadioSelect选项中单独添加图像?

时间:2018-04-14 10:35:13

标签: python django

forms.py

from django import forms


BINDING = (
    ('1','Coil Bound Paperback'),
    ('2','Perfect Bound Paperback'),
    ('3','Saddle Stitch Paperback'),
)

class BindingForm(forms.Form):
    my_binding_choice = forms.ChoiceField(choices=BINDING,widget 
=forms.RadioSelect())

views.py

from django.shortcuts import render,render_to_response
from .forms import MyForm,BindingForm


def my_binding_view(request):
    form = BindingForm()
    return render(request,'base.html',{'binding_form':form})

template.html

{% for radio in binding_form %}
    <div class="myradio">
        {{ radio }}
    </div>
{% endfor %}

&#39;&#39;&#39;但我想在我的选择中添加图片,以便在放射选择列表中显示,或者可以通过其他方法实现?&#39;&#39; &#39;

1 个答案:

答案 0 :(得分:0)

您可以继承RadioSelect and specify your own option_template_name,这将决定每个选项的呈现方式:

class CustomRadioSelect(RadioSelect):
    option_template_name = 'myapp/radio_option_custom.html'

# Then use this widget in your form
class BindingForm(forms.Form):
    my_binding_choice = forms.ChoiceField(choices=BINDING, 
                                          widget=CustomRadioSelect())

然后提供模板myapp/radio_option_custom.html,以您想要的方式呈现每个选项。默认模板为here,因此您可以从中开始并添加所需的任何位。