在django中将自定义html添加到choicefield标签

Mav*_*ick 6 django django-forms django-formwizard django-1.5

我现在正在努力满足要求,我想在选择字段标签上添加一个图像,我真的不知道如何做到这一点.我正在使用django表单向导来呈现表单.这是显示我想要实现的目标的图像: 在此输入图像描述

这就是我现在所拥有的(使内置单选按钮,我知道它可以通过css实现): 在此输入图像描述

这是forms.py:

from django import forms
from django.utils.translation import gettext as _


CHOICES=[('0','Pay by card'), ('1','Invoice')]




class PaymentForm(forms.Form):
    title = 'payment'
    payment_method = forms.ChoiceField(label = _("Payment Options"), choices=CHOICES, widget=forms.RadioSelect(), required = True)
Run Code Online (Sandbox Code Playgroud)

我使用向导形式渲染:

 {{ wizard.form.payment_method.label_tag }}
                                {{ wizard.form.payment_method|safe }}
                                {{ wizard.form.payment.errors}}
Run Code Online (Sandbox Code Playgroud)

除了自定义小部件之外,任何人都对此有任何建议吗?

lal*_*alo 2

1)很快(但我不确定)调用一个“用卡支付”的函数并返回<img>...您需要的所有内容。

2)你可以做像@Gahbu所说的东西

3)长[我认为更好,但未经测试:(]:制作一个渲染器:

from myapp.my_widgets import CardsRadioFieldRenderer

CARD_CHOICE = '0'

CHOICES=[(CARD_CHOICE,'Pay by card'), ('1','Invoice')]

class PaymentForm(forms.Form):
    title = 'payment'
    payment_method = forms.ChoiceField(label = _("Payment Options"), choices=CHOICES,widget=forms.RadioSelect(renderer=CardsRadioFieldRenderer), required = True)

# myapp/my_widgets.py

class CardRadioInput(RadioInput):
    def __init__(self, name, value, attrs, choice, index):
        self.name, self.value = name, value
        self.attrs = attrs
        choice_value = force_text(choice[0])
        self.choice_value = choice_value
        if choice_value == CARD_CHOICE:
            choice_label = force_text(self.get_html_for_card_choice())
        else:
            choice_label = force_text(choice[1])
        self.choice_label = choice_label
        self.index = index

   def get_html_for_card_choice(self):
        #some logic to get the images tags (<img ...> <img ...>)
        return text


class CardsRadioFieldRenderer(RadioFieldRenderer):
    def __getitem__(self, idx):
        choice = self.choices[idx] # Let the IndexError propogate
        return CardRadioInput(self.name, self.value, self.attrs.copy(), choice, idx)
Run Code Online (Sandbox Code Playgroud)