20 lines
811 B
Python
20 lines
811 B
Python
|
from django import forms
|
||
|
from django.contrib.humanize.templatetags.humanize import apnumber
|
||
|
from django.template.defaultfilters import pluralize
|
||
|
|
||
|
|
||
|
class MultiSelectFormField(forms.MultipleChoiceField):
|
||
|
widget = forms.CheckboxSelectMultiple
|
||
|
|
||
|
def __init__(self, *args, **kwargs):
|
||
|
self.max_choices = kwargs.pop('max_choices', 0)
|
||
|
super(MultiSelectFormField, self).__init__(*args, **kwargs)
|
||
|
|
||
|
def clean(self, value):
|
||
|
if not value and self.required:
|
||
|
raise forms.ValidationError(self.error_messages['required'])
|
||
|
if value and self.max_choices and len(value) > self.max_choices:
|
||
|
raise forms.ValidationError('You must select a maximum of %s choice%s.'
|
||
|
% (apnumber(self.max_choices), pluralize(self.max_choices)))
|
||
|
return value
|