In Django is there a way to display choices as checkboxes?

前端 未结 2 902
离开以前
离开以前 2020-12-12 15:16

In the admin interface and newforms there is the brilliant helper of being able to define choices. You can use code like this:

APPROVAL_CHOICES = (
    (\'ye         


        
2条回答
  •  执笔经年
    2020-12-12 15:40

    In terms of the forms library, you would use the MultipleChoiceField field with a CheckboxSelectMultiple widget to do that. You could validate the number of choices which were made by writing a validation method for the field:

    class MyForm(forms.Form):
        my_field = forms.MultipleChoiceField(choices=SOME_CHOICES, widget=forms.CheckboxSelectMultiple())
    
        def clean_my_field(self):
            if len(self.cleaned_data['my_field']) > 3:
                raise forms.ValidationError('Select no more than 3.')
            return self.cleaned_data['my_field']
    

    To get this in the admin application, you'd need to customise a ModelForm and override the form used in the appropriate ModelAdmin.

提交回复
热议问题