【问题标题】:Django - Forms Widget TypeChoiceField - how to set id for two radio buttonsDjango - 表单小部件 TypeChoiceField - 如何为两个单选按钮设置 id
【发布时间】:2011-12-26 19:32:46
【问题描述】:

我正在使用带有 TypeChoiceField 的表单,这是表单的代码:

class AnagraficaForm(forms.Form):
    usertype = ((1,'Privato'),(0,'Libero professionista/Azienda'))
    nome = forms.CharField(max_length=100)
    cognome = forms.CharField(max_length=100)
    telefono = forms.CharField(max_length=50,required=False)
    email= forms.EmailField(max_length=100,required=False)
    indirizzo = forms.CharField(max_length=100)
    cap = ITZipCodeField(required=False)
    citta = forms.CharField(max_length=100)
    codfisc = ITSocialSecurityNumberField(required=False)
    piva = ITVatNumberField(required=False)

    ragsociale = forms.CharField(max_length=100)
    is_privato = forms.TypedChoiceField(
        initial=1,
        coerce=lambda x: bool(int(x)),
        choices=usertype,
        #using custom renderer to display radio buttons on the same line
        widget=forms.RadioSelect(renderer=HorizRadioRenderer)
    )

现在我正在尝试为显示的两个单选按钮设置自定义 ID,但我还没有找到正确的方法。有什么想法吗?

谢谢 - 卢克

【问题讨论】:

    标签: django django-models django-forms django-templates django-views


    【解决方案1】:

    您需要自定义渲染器HorizRadioRendererrender 方法,因为您需要为每组单选按钮自定义它。如果它只是一个字段,您可以使用 attrs 参数来自定义 id。

    【讨论】:

    • tnx 为您的回复。这是自定义渲染器类:pastebin.com/9x8HPgT1 但老实说,我不明白在哪里修改代码,因为它只是在互联网上找到的代码 sn-p。我还尝试修改表单中的 usertype 参数,并传递两个 attrs 字典(因为我需要为每个单选按钮提供两个不同的 id 和名称)但它没有用......有什么帮助吗?
    猜你喜欢
    • 1970-01-01
    • 2017-09-30
    • 2015-03-11
    • 2023-02-22
    • 2015-05-24
    • 2014-12-30
    • 2017-10-15
    • 2016-09-15
    • 1970-01-01
    相关资源
    最近更新 更多