如何在Django中将选择显示为复选框?

时间:2018-09-02 13:45:42

标签: django

我有一个在forms.py中覆盖并在前端显示的模型。因此,choices字段将作为下拉列表出现,但我希望它呈现为复选框,我尝试通过用forms.CheckBoxInput()覆盖表单来做到这一点,但它只是显示了针对各个选项的区域热点复选框。因此,请指导我如何实现。

models.py

region_choices = (
    ('AF', 'Africa'),
    ('AS', 'Asia'),
    ('EU', 'Europe'),
    ('NA', 'North America'),
    ('SA', 'South America'),
    ('OC', 'Oceania'),
    ('AN', 'Antarctica'),
)

class Registeration(models.Model):
    username = models.CharField(max_length=100)
    email = models.EmailField()
    password = models.CharField(max_length=100)
    confirm_pasword = models.CharField(max_length=100)
    region = models.CharField(choices=region_choices,max_length=10)
    terms_confirmed = models.BooleanField(default=False)


    def __str__(self):
        return self.username

forms.py

class RegistrationForm(forms.ModelForm):

    def __init__(self,*args,**kwargs):
        super(RegistrationForm,self).__init__(*args,**kwargs)
        self.fields['region'].widget = forms.CheckboxInput()


    class Meta:
        model = Registeration
        fields = '__all__'

html

<form>
    {% csrf_token %}
    {{form.as_p}}
    <input type="submit" value="ok">
</form>

1 个答案:

答案 0 :(得分:2)

您可以将forms.MultipleChoiceFieldwidget=forms.CheckboxSelectMultiple()一起使用。

class RegistrationForm(forms.ModelForm):

    region = forms.MultipleChoiceField(choices=region_choices, widget=forms.CheckboxSelectMultiple())

    def clean_region(self):
        if len(self.cleaned_data['region']) > 1:
            raise forms.ValidationError('Select only 1 option.')
        return self.cleaned_data['region']

    class Meta:
        model = Registeration
        fields = '__all__'

class RegistrationForm(forms.ModelForm):

    def __init__(self,*args,**kwargs):
        super(RegistrationForm,self).__init__(*args,**kwargs)
        self.fields['region']= forms.MultipleChoiceField(choices=region_choices, widget=forms.CheckboxSelectMultiple())

    def clean_region(self):
        if len(self.cleaned_data['region']) > 1:
            raise forms.ValidationError('Select only 1 option.')
        return self.cleaned_data['region']

    class Meta:
        model = Registeration
        fields = '__all__'