Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

django

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 = (     ('yes', 'Yes'),     ('no', 'No'),     ('cancelled', 'Cancelled'), )  client_approved = models.CharField(choices=APPROVAL_CHOICES) 

to create a drop down box in your form and force the user to choose one of those options.

I'm just wondering if there is a way to define a set of choices where multiple can be chosen using checkboxes? (Would also be nice to be able to say that the user can select a maximum number of them.) It seems like it's a feature that is probably implemented, it's just I can't seem to find it in the documentation.

like image 688
sesh Avatar asked Sep 29 '08 06:09

sesh


People also ask

How do you check checkbox is checked or not in Django?

POST or None) if request. method == "POST": if form. is_valid(): ... if request. POST["something_truthy"]: # Checkbox was checked ...

How do I use widgets in Django?

Custom form with fields Widgets We create a two form-field using the CharField() field that takes in a text input. We can override the default widget of each field for various uses. The CharField() has a default widget TextInput which is the equivalent of rendering HTML code <input type = "text">.


1 Answers

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.

like image 161
Jonny Buchanan Avatar answered Sep 29 '22 19:09

Jonny Buchanan