【问题标题】:Is it possible to map a field to a custom template radio button group?是否可以将字段映射到自定义模板单选按钮组?
【发布时间】:2023-01-24 23:10:08
【问题描述】:

标题中的问题。

我有这样的表格

class SelectTypeForm(forms.Form):

the_type = forms.CharField(max_length=100)

我有一个带有单选按钮组的自定义模板。怎样才能让字段得到选中的值呢?

【问题讨论】:

    标签: django django-formtools


    【解决方案1】:

    您可以使用内置的单选小部件并将自定义模板路径传递给表单字段定义中的 template_name 参数。

    例如:

    from django import forms
    
    class MyForm(forms.Form):
        my_field = forms.ChoiceField(
            widget=forms.RadioSelect(template_name='my_app/custom_radio_template.html'),
            choices=(('option1', 'Option 1'), ('option2', 'Option 2')),
        )
    

    然后您可以在中创建自定义单选按钮模板my_app/templates/my_app/custom_radio_template.html并使用{{ forloop.counter }}变量以正确输出单选按钮值和标签。

    【讨论】:

    • 感谢您的输入,我正在尝试这个,但它不喜欢 template_name 参数..知道吗? widget=forms.RadioSelect(template_name='sites/site_create_type.html'), TypeError: ChoiceWidget.__init__() 有一个意外的关键字参数'template_name'
    • @Chris 请检查我的其他答案。
    【解决方案2】:

    template_name 参数不是 RadioSelect 小部件的有效参数。您应该使用 attrs 参数而不是 template_name。

    class MyForm(forms.Form):
        my_field = forms.ChoiceField(
            widget=forms.RadioSelect(attrs={'template': 'my_app/custom_radio_template.html'}),
            choices=(('option1', 'Option 1'), ('option2', 'Option 2')),
        )
    

    您还应注意,attrs 值是一个字典,键“template”不是有效的 HTML 属性。

    class MyForm(forms.Form):
        my_field = forms.ChoiceField(
            widget=forms.RadioSelect(attrs={'class': 'custom-radio'}),
            choices=(('option1', 'Option 1'), ('option2', 'Option 2')),
        )
    

    然后在您的模板中,您可以使用该类来定位单选按钮并应用自定义样式或布局。

    {% for radio in form.my_field %}
        <div class="custom-radio">
            {{ radio }}
        </div>
    {% endfor %}
    

    重要的是要注意 attrs 参数被传递给小部件,因此它会影响所有呈现的元素,而不仅仅是单选按钮,因此您应该在 CSS 中使用该类来仅针对单选按钮。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多