37 lines
1.6 KiB
Python
37 lines
1.6 KiB
Python
# -*- coding: utf-8 -*-
|
|
# Copyright (c) 2012-2013 by Pablo Martín <goinnn@gmail.com>
|
|
#
|
|
# This program is free software: you can redistribute it and/or modify
|
|
# it under the terms of the GNU Lesser General Public License as published by
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
# (at your option) any later version.
|
|
#
|
|
# This program is distributed in the hope that it will be useful,
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
# GNU Lesser General Public License for more details.
|
|
#
|
|
# You should have received a copy of the GNU Lesser General Public License
|
|
# along with this programe. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
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
|