当我手动编写选项时,如何使RadioSelect遍历特定字段的每个选项?

时间:2019-05-21 02:37:16

标签: python-3.x django-models django-forms

我有一个收集潜在客户联系信息的模型。其中之一与月份有关,我正在尝试让它们显示为单选按钮。我仅使用RadioSelect选项来发现没有附加的单选按钮。

我发现了如何使用Django文档将表单的每个字段手动输入到页面中。我做到了,它奏效了,但现在显示了全部12个月,超过12倍。我不知道如何一次显示全部12个月。

forms.py

from django.forms import ModelForm
from django import forms
from .models import CustomerData, Ebook

MONTH_CHOICES = [
    ('January', 'January'),
    ('February', 'February'),
    ('March','March'),
    ('April', 'April'),
    ('May', 'May'),
    ('June','June'),
    ('July', 'July'),
    ('August', 'August'),
    ('September','September'),
    ('October','October'),
    ('November','November'),
    ('December','December')
]


class ContactForm(ModelForm):
    month = forms.ChoiceField(label='', choices=MONTH_CHOICES, widget=forms.RadioSelect(), error_messages={'required' : 'Month is Required'})
    phone = forms.CharField(required=False)
    firstname = forms.CharField(label='', error_messages={'required': 'First Name Required'})
    lastname = forms.CharField(label='', error_messages={'required': 'Last Name Required'})
    npo = forms.CharField(label='', error_messages={'required': 'Organization Required'})
    email = forms.CharField(label='', error_messages={'required': 'Email Required'})
    class Meta:
        model = CustomerData
        fields = ['firstname', 'lastname', 'npo', 'email', 'phone', 'month']

index.html

<div class="fieldWrapper">
        {{ form.month.errors }}
<label for="{{ form.subject.id_for_label }}">Month:</label>
    {% for month in form.month %}
        <label>
         <input name="group1" type="radio" />
         <span> {{ form.month }} </span>
        </label>
    {% endfor %}
</div>

我需要这样做来重复几个月,并只显示一次它们

这是我所看到的图像

12 months 12 times

1 个答案:

答案 0 :(得分:0)

无视。我想到了。这是任何可能偶然发现此问题的人的解决方案。

    <!-- Month -->
<div class="fieldWrapper">
        {{ form.month.errors }}
<label for="{{ form.subject.id_for_label }}">Month:</label>
<br>
    {% for month, monthb in form.fields.month.choices %}
        <label>
         <input name="group1" type="radio" />
         <span> {{month}} </span>
        </label>
    {% endfor %}
</div>

我需要有两个引用,并且在span部分中仅调用其中一个。我还需要将选择添加到for循环初始化中。