Is there a way in Django to display options as checkboxes?

The admin interface and newforms have a brilliant helper in the ability to define options. You can use this code:

APPROVAL_CHOICES = ( ('yes', 'Yes'), ('no', 'No'), ('cancelled', 'Cancelled'), ) client_approved = models.CharField(choices=APPROVAL_CHOICES) 

to create a drop-down list on the form and force the user to select one of these options.

I'm just wondering if there is a way to define a set of options where several can be selected using checkboxes? (It would also be nice to be able to say that the user can select the maximum number of them.) It seems that this is a function that is probably implemented, I just can not find it in the documentation.

+41
python django
Sep 29 '08 at 6:53
source share
2 answers

In terms of a form library, you should use the MultipleChoiceField field with CheckboxSelectMultiple . You can check the number of options that were made by writing a check 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 need to configure ModelForm and override the form used in the corresponding ModelAdmin .

+75
Sep 29 '08 at 7:17
source share

@JonnyBuchanan gave the correct answer.

But if you need this in django admin for many models, and you (like me) are too lazy to set up ModelForm and override the correct methods inside the ModelAdmin class, you can use this approach:

http://www.abidibo.net/blog/2013/04/10/convert-select-multiple-widget-checkboxes-django-admin-form/

0
Nov 24 '15 at 15:29
source share



All Articles