django-multiselectfield/multiselectfield/forms/fields.py

37 lines
1.6 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
2014-10-13 13:57:44 +00:00
# Copyright (c) 2012 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/>.
2012-09-27 14:02:41 +00:00
from django import forms
from ..utils import get_max_length
2016-11-29 09:07:43 +00:00
from ..validators import MaxValueMultiFieldValidator, MinChoicesValidator, MaxChoicesValidator
2012-09-27 14:02:41 +00:00
class MultiSelectFormField(forms.MultipleChoiceField):
widget = forms.CheckboxSelectMultiple
def __init__(self, *args, **kwargs):
2016-11-29 09:07:43 +00:00
self.min_choices = kwargs.pop('min_choices', None)
self.max_choices = kwargs.pop('max_choices', None)
self.max_length = kwargs.pop('max_length', None)
2012-09-27 14:02:41 +00:00
super(MultiSelectFormField, self).__init__(*args, **kwargs)
self.max_length = get_max_length(self.choices, self.max_length)
self.validators.append(MaxValueMultiFieldValidator(self.max_length))
if self.max_choices is not None:
self.validators.append(MaxChoicesValidator(self.max_choices))
2016-11-29 09:07:43 +00:00
if self.min_choices is not None:
self.validators.append(MinChoicesValidator(self.min_choices))