django-multiselectfield/src/multiselectfield/forms/fields.py

20 lines
811 B
Python
Raw Normal View History

2012-09-27 14:02:41 +00:00
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