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

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

    ('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.

Asked by: Maya961 | Posted: 05-10-2021

Answer 1

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.

Answered by: Julia207 | Posted: 06-11-2021

Answer 2

@JonnyBuchanan gave the right answer.

But if you need this in the django admin for many models, and you're (like me) too lazy to customize a ModelForm and ovverride the right methods inside the ModelAdmin class, you can use this approach:

Answered by: David466 | Posted: 06-11-2021

Similar questions

python - DJANGO - How to display a text form field next to checked checkboxes

I am creating an application that allows you to add predefined services to an invoice. When creating a new invoice, you can select services using checkboxes. I would like to add the text field to specify the quantity after selecting the checkbox. So you check the checkbox and text field appears next to it where you can enter the quantity. I would like to store this data in the database after creating a new invoice. I am no...

html - Python - reading checkboxes

I have a few checkboxes with common name and individual variables (ID). How can I in python read them as list? Now I'm using checkbox= request.POST["common_name"] It isn't work properly, checkbox variable store only the last checked box instead of any list or something.

python - PyQt: change the alignment of checkboxes in a QTableView

I have a QTableView with checkbox, but the checkbox is aligned left, and I need to align it center. I tried this, but I have a problem with the "check" function: def drawCheck(self, painter, option, rect, state): textMargin =

python - How do I use pylons (paste) webtest with multiple checkboxes with the same name?

Suppose I have a form like this: <form id='myform'> Favorite colors? <input type='checkbox' name='color' value='Green'>Green <input type='checkbox' name='color' value='Blue'>Blue <input type='checkbox' name='color' value='Red'>Red <input type='submit' value='Submit'> </form> How do I use webtest's form library to test submitting multi...

python - Remove items with checkboxes in Django forms

I'm writing a form with Django. The form is a model form for a certain model, Experiment. Each Experiment has several TimeSlot models associated with it, defined with a ForeignKey('Experiment'). I'd like to have a form with the option to remove one or more TimeSlot instances from the EditExperimentForm by checking boxes. Currently, I def...

python - CherryPy - saving checkboxes selection to variables

I'm trying to build a simple webpage with multiple checkboxes, a Textbox and a submit buttom. I've just bumped into web programing in Python and am trying to figure out out to do it with CherryPy. I need to associate each checkbox to a variable so my .py file knows which ones were selected when clicking the 'Start button'. Can someone please give some code example ? Do I have any advantage including some Py...

python - Django: writing a view to delete an item with checkboxes

I need help writing a view that gets the POST data which then finds out which checkboxes have been checked, and then deletes the items from the database matched by id. Originally, This was a checkbox problem. In a edit order form, there are a list of items. Now I CAN remove the item using a bit of javascript but it does not get save because I need to remove it completly from my database. I tried using my edit order views t...

python - Checkboxes in a Combobox using PyQt

I need to implement a drop down list that contains CheckBoxes, much like having the entries in a ComboBox being CheckBoxes. But QComboBox doesn't accept QCheckBox as its member and I couldn't find any alternate solution. I found an implementation in C++ on the Qt Wiki, but don't know how to port it...

python - Variable size list of Checkboxes in Tkinter?

I'm working on a programming task. I'm working in Python, and using Tkinter for our GUI. I cannot change language or GUI tool, nor can I use any additional packages (for example Tix). I need to make a list of items to pull. The first thing I thought of was a check box. However, so far as I know, Tkinter does not have anything that supports a large number(100+) of check boxes....

c++ - QTreeView Checkboxes

I know this has been asked a bunch of times, but I cant seem to find anything relevant. Using the simpletreemodel tutorial that comes packaged with Qt, how would I add checkboxes?

checkbox - How do I create multiple checkboxes from a list in a for loop in python tkinter

I have a list of variable length and want to create a checkbox (with python TKinter) for each entry in the list (each entry corresponds to a machine which should be turned on or off with the checkbox -> change the value in the dictionary). print enable {'ID1050': 0, 'ID1106': 0, 'ID1104': 0, 'ID1102': 0} (example, can be any length) now the relevant code: for machi...

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python