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

2024/11/20 16:24:44

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.

Answer

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.

https://en.xdnf.cn/q/26304.html

Related Q&A

How to get the first 2 letters of a string in Python?

Lets say I have a string str1 = "TN 81 NZ 0025" two = first2(str1) print(two) # -> TNHow do I get the first two letters of this string? I need the first2 function for this.

Python sqlite3 version

Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >…

Python debugger (pdb) stopped handlying up/down arrows, shows ^[[A instead

I am using python 2.6 in a virtualenv on an Ubuntu Linux 11.04 (natty) machine. I have this code in my (django) python code:import pdb ; pdb.set_trace()in order to launch the python debugger (pdb).Up u…

Un-persisting all dataframes in (py)spark

I am a spark application with several points where I would like to persist the current state. This is usually after a large step, or caching a state that I would like to use multiple times. It appears …

Can pip (or setuptools, distribute etc...) list the license used by each installed package?

Im trying to audit a Python project with a large number of dependencies and while I can manually look up each projects homepage/license terms, it seems like most OSS packages should already contain the…

Convert DataFrameGroupBy object to DataFrame pandas

I had a dataframe and did a groupby in FIPS and summed the groups that worked fine.kl = ks.groupby(FIPS)kl.aggregate(np.sum)I just want a normal Dataframe back but I have a pandas.core.groupby.DataFram…

Correct way to obtain confidence interval with scipy

I have a 1-dimensional array of data:a = np.array([1,2,3,4,4,4,5,5,5,5,4,4,4,6,7,8])for which I want to obtain the 68% confidence interval (ie: the 1 sigma).The first comment in this answer states that…

How to supply a mock class method for python unit test?

Lets say I have a class like this. class SomeProductionProcess(CustomCachedSingleTon):@classmethoddef loaddata(cls):"""Uses an iterator over a large file in Production for the Data pipel…

View pdf image in an iPython Notebook

The following code allows me to view a png image in an iPython notebook. Is there a way to view pdf image? I dont need to use IPython.display necessarily. I am looking for a way to print a pdf image i…

Is the use of del bad?

I commonly use del in my code to delete objects:>>> array = [4, 6, 7, hello, 8] >>> del(array[array.index(hello)]) >>> array [4, 6, 7, 8] >>> But I have heard many …