django-orchestra/orchestra/models/fields.py

68 lines
2.5 KiB
Python
Raw Normal View History

2014-09-26 15:05:20 +00:00
from django.core import exceptions
2014-05-08 16:59:35 +00:00
from django.db import models
from django.utils.text import capfirst
from ..forms.fields import MultiSelectFormField
from ..utils.apps import isinstalled
2015-04-02 16:14:55 +00:00
class MultiSelectField(models.CharField, metaclass=models.SubfieldBase):
2014-05-08 16:59:35 +00:00
def formfield(self, **kwargs):
defaults = {
'required': not self.blank,
'label': capfirst(self.verbose_name),
'help_text': self.help_text,
'choices': self.choices
}
if self.has_default():
2015-04-03 13:03:08 +00:00
defaults['initial'] = self.get_default()
2014-05-08 16:59:35 +00:00
defaults.update(kwargs)
return MultiSelectFormField(**defaults)
def get_db_prep_value(self, value, connection=None, prepared=False):
2015-04-02 16:14:55 +00:00
if isinstance(value, str):
2014-05-08 16:59:35 +00:00
return value
2015-04-08 14:41:09 +00:00
else:
2014-05-08 16:59:35 +00:00
return ','.join(value)
def to_python(self, value):
2014-11-13 15:34:00 +00:00
if value:
2015-04-03 13:03:08 +00:00
# if isinstance(value, tuple) and value[0].startswith('('):
# # Workaround unknown bug on default model values
# # [u"('SUPPORT'", u" 'ADMIN'", u" 'BILLING'", u" 'TECH'", u" 'ADDS'", u" 'EMERGENCY')"]
# value = list(eval(', '.join(value)))
if isinstance(value, str):
return value.split(',')
return value
2014-11-13 15:34:00 +00:00
return []
2014-05-08 16:59:35 +00:00
def contribute_to_class(self, cls, name):
super(MultiSelectField, self).contribute_to_class(cls, name)
if self.choices:
def func(self, field=name, choices=dict(self.choices)):
2014-11-13 15:34:00 +00:00
return ','.join([choices.get(value, value) for value in getattr(self, field)])
2014-05-08 16:59:35 +00:00
setattr(cls, 'get_%s_display' % self.name, func)
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):
msg = self.error_messages['invalid_choice'] % value
raise exceptions.ValidationError(msg)
def get_choices_selected(self, arr_choices=''):
if not arr_choices:
return False
2015-04-04 17:44:07 +00:00
return [value for value, __ in arr_choices]
2014-05-08 16:59:35 +00:00
2014-07-10 15:19:06 +00:00
class NullableCharField(models.CharField):
def get_db_prep_value(self, value, connection=None, prepared=False):
return value or None
2014-05-08 16:59:35 +00:00
if isinstalled('south'):
from south.modelsinspector import add_introspection_rules
2014-07-09 16:17:43 +00:00
add_introspection_rules([], ["^orchestra\.models\.fields\.MultiSelectField"])
2014-07-10 15:19:06 +00:00
add_introspection_rules([], ["^orchestra\.models\.fields\.NullableCharField"])