2013-09-11 08:49:03 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
2014-10-13 13:57:44 +00:00
|
|
|
# Copyright (c) 2012 by Pablo Martín <goinnn@gmail.com>
|
2013-09-11 08:49:03 +00:00
|
|
|
#
|
|
|
|
# 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/>.
|
|
|
|
|
|
|
|
import sys
|
|
|
|
|
2016-09-22 20:12:56 +00:00
|
|
|
from django import VERSION
|
2013-11-26 19:45:46 +00:00
|
|
|
|
2012-09-27 14:02:41 +00:00
|
|
|
from django.db import models
|
|
|
|
from django.utils.text import capfirst
|
|
|
|
from django.core import exceptions
|
|
|
|
|
2013-11-26 17:56:37 +00:00
|
|
|
from ..forms.fields import MultiSelectFormField, MaxChoicesValidator
|
|
|
|
from ..utils import get_max_length
|
|
|
|
from ..validators import MaxValueMultiFieldValidator
|
2012-09-27 14:02:41 +00:00
|
|
|
|
2016-09-22 20:12:56 +00:00
|
|
|
if sys.version_info < (3,):
|
2013-09-11 08:49:03 +00:00
|
|
|
string_type = unicode
|
|
|
|
else:
|
2013-11-30 18:31:14 +00:00
|
|
|
string_type = str
|
2013-09-11 08:49:03 +00:00
|
|
|
|
|
|
|
# Code from six egg https://bitbucket.org/gutworth/six/src/a3641cb211cc360848f1e2dd92e9ae6cd1de55dd/six.py?at=default
|
|
|
|
|
|
|
|
|
|
|
|
def add_metaclass(metaclass):
|
|
|
|
"""Class decorator for creating a class with a metaclass."""
|
|
|
|
def wrapper(cls):
|
|
|
|
orig_vars = cls.__dict__.copy()
|
|
|
|
orig_vars.pop('__dict__', None)
|
|
|
|
orig_vars.pop('__weakref__', None)
|
|
|
|
for slots_var in orig_vars.get('__slots__', ()):
|
|
|
|
orig_vars.pop(slots_var)
|
|
|
|
return metaclass(cls.__name__, cls.__bases__, orig_vars)
|
|
|
|
return wrapper
|
|
|
|
|
2012-09-27 14:02:41 +00:00
|
|
|
|
2013-11-19 18:29:20 +00:00
|
|
|
class MultiSelectField(models.CharField):
|
2012-09-27 14:02:41 +00:00
|
|
|
""" Choice values can not contain commas. """
|
|
|
|
|
2013-11-26 17:56:37 +00:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
self.max_choices = kwargs.pop('max_choices', None)
|
|
|
|
super(MultiSelectField, self).__init__(*args, **kwargs)
|
|
|
|
self.max_length = get_max_length(self.choices, self.max_length)
|
|
|
|
self.validators[0] = MaxValueMultiFieldValidator(self.max_length)
|
|
|
|
if self.max_choices is not None:
|
|
|
|
self.validators.append(MaxChoicesValidator(self.max_choices))
|
|
|
|
|
2012-09-27 14:02:41 +00:00
|
|
|
def get_choices_default(self):
|
|
|
|
return self.get_choices(include_blank=False)
|
|
|
|
|
2013-11-30 18:57:20 +00:00
|
|
|
def get_choices_selected(self, arr_choices):
|
|
|
|
choices_selected = []
|
2012-09-27 14:02:41 +00:00
|
|
|
for choice_selected in arr_choices:
|
2013-11-30 18:57:20 +00:00
|
|
|
choices_selected.append(string_type(choice_selected[0]))
|
|
|
|
return choices_selected
|
2012-09-27 14:02:41 +00:00
|
|
|
|
|
|
|
def value_to_string(self, obj):
|
|
|
|
value = self._get_val_from_obj(obj)
|
2012-09-27 15:57:02 +00:00
|
|
|
return self.get_prep_value(value)
|
2012-09-27 14:02:41 +00:00
|
|
|
|
|
|
|
def validate(self, value, model_instance):
|
|
|
|
arr_choices = self.get_choices_selected(self.get_choices_default())
|
|
|
|
for opt_select in value:
|
|
|
|
if (opt_select not in arr_choices):
|
2016-09-22 20:12:56 +00:00
|
|
|
if VERSION >= (1, 6):
|
2013-11-26 19:45:46 +00:00
|
|
|
raise exceptions.ValidationError(self.error_messages['invalid_choice'] % {"value": value})
|
|
|
|
else:
|
|
|
|
raise exceptions.ValidationError(self.error_messages['invalid_choice'] % value)
|
2013-11-30 18:25:11 +00:00
|
|
|
|
|
|
|
def get_default(self):
|
|
|
|
default = super(MultiSelectField, self).get_default()
|
|
|
|
if isinstance(default, int):
|
|
|
|
default = string_type(default)
|
|
|
|
return default
|
2012-09-27 14:02:41 +00:00
|
|
|
|
|
|
|
def formfield(self, **kwargs):
|
2013-11-26 17:56:37 +00:00
|
|
|
defaults = {'required': not self.blank,
|
|
|
|
'label': capfirst(self.verbose_name),
|
|
|
|
'help_text': self.help_text,
|
|
|
|
'choices': self.choices,
|
|
|
|
'max_length': self.max_length,
|
|
|
|
'max_choices': self.max_choices}
|
2012-09-27 14:02:41 +00:00
|
|
|
if self.has_default():
|
|
|
|
defaults['initial'] = self.get_default()
|
|
|
|
defaults.update(kwargs)
|
|
|
|
return MultiSelectFormField(**defaults)
|
|
|
|
|
2012-09-27 15:57:02 +00:00
|
|
|
def get_prep_value(self, value):
|
2013-12-31 08:54:12 +00:00
|
|
|
return '' if value is None else ",".join(value)
|
2012-09-27 14:02:41 +00:00
|
|
|
|
2014-11-28 05:54:30 +00:00
|
|
|
def get_db_prep_value(self, value, connection, prepared=False):
|
2014-12-20 03:38:16 +00:00
|
|
|
if not prepared and not isinstance(value, string_type):
|
2014-11-28 05:54:30 +00:00
|
|
|
value = self.get_prep_value(value)
|
|
|
|
return value
|
|
|
|
|
2012-09-27 14:02:41 +00:00
|
|
|
def to_python(self, value):
|
2013-12-31 08:54:12 +00:00
|
|
|
if value:
|
2012-09-27 14:02:41 +00:00
|
|
|
return value if isinstance(value, list) else value.split(',')
|
2015-06-03 18:21:12 +00:00
|
|
|
return []
|
2012-09-27 14:02:41 +00:00
|
|
|
|
2016-09-22 10:15:34 +00:00
|
|
|
def from_db_value(self, value, expression, connection, context):
|
|
|
|
if value is None:
|
|
|
|
return value
|
|
|
|
return self.to_python(value)
|
|
|
|
|
2012-09-27 14:02:41 +00:00
|
|
|
def contribute_to_class(self, cls, name):
|
|
|
|
super(MultiSelectField, self).contribute_to_class(cls, name)
|
|
|
|
if self.choices:
|
2014-05-14 07:50:59 +00:00
|
|
|
def get_list(obj):
|
2013-11-26 19:04:41 +00:00
|
|
|
fieldname = name
|
|
|
|
choicedict = dict(self.choices)
|
|
|
|
display = []
|
2014-07-21 11:52:30 +00:00
|
|
|
if getattr(obj, fieldname):
|
|
|
|
for value in getattr(obj, fieldname):
|
|
|
|
item_display = choicedict.get(value, None)
|
|
|
|
if item_display is None:
|
|
|
|
try:
|
|
|
|
item_display = choicedict.get(int(value), value)
|
|
|
|
except (ValueError, TypeError):
|
|
|
|
item_display = value
|
|
|
|
display.append(string_type(item_display))
|
2014-05-14 07:50:59 +00:00
|
|
|
return display
|
2014-10-13 14:16:06 +00:00
|
|
|
|
2014-05-14 07:50:59 +00:00
|
|
|
def get_display(obj):
|
|
|
|
return ", ".join(get_list(obj))
|
2014-10-13 14:16:06 +00:00
|
|
|
|
2014-05-14 07:50:59 +00:00
|
|
|
setattr(cls, 'get_%s_list' % self.name, get_list)
|
2013-11-26 19:04:41 +00:00
|
|
|
setattr(cls, 'get_%s_display' % self.name, get_display)
|
2013-09-11 08:49:03 +00:00
|
|
|
|
2016-09-22 20:12:56 +00:00
|
|
|
if VERSION < (1, 8):
|
2016-09-22 10:15:34 +00:00
|
|
|
MultiSelectField = add_metaclass(models.SubfieldBase)(MultiSelectField)
|
2013-09-11 08:49:03 +00:00
|
|
|
|
2012-09-27 14:12:55 +00:00
|
|
|
try:
|
|
|
|
from south.modelsinspector import add_introspection_rules
|
|
|
|
add_introspection_rules([], ['^multiselectfield\.db.fields\.MultiSelectField'])
|
|
|
|
except ImportError:
|
|
|
|
pass
|