Merge pull request #21 from vasyabigi/master

Fixed prep/to_python values of model field.
This commit is contained in:
Pablo Martín 2014-10-13 14:46:10 +02:00
commit b3ea613558

View file

@ -98,12 +98,11 @@ class MultiSelectField(models.CharField):
return MultiSelectFormField(**defaults) return MultiSelectFormField(**defaults)
def get_prep_value(self, value): def get_prep_value(self, value):
return ",".join(value) return '' if value is None else ",".join(value)
def to_python(self, value): def to_python(self, value):
if value is not None: if value:
return value if isinstance(value, list) else value.split(',') return value if isinstance(value, list) else value.split(',')
return ''
def contribute_to_class(self, cls, name): def contribute_to_class(self, cls, name):
super(MultiSelectField, self).contribute_to_class(cls, name) super(MultiSelectField, self).contribute_to_class(cls, name)
@ -112,14 +111,15 @@ class MultiSelectField(models.CharField):
fieldname = name fieldname = name
choicedict = dict(self.choices) choicedict = dict(self.choices)
display = [] display = []
for value in getattr(obj, fieldname): if getattr(obj, fieldname):
item_display = choicedict.get(value, None) for value in getattr(obj, fieldname):
if item_display is None: item_display = choicedict.get(value, None)
try: if item_display is None:
item_display = choicedict.get(int(value), value) try:
except (ValueError, TypeError): item_display = choicedict.get(int(value), value)
item_display = value except (ValueError, TypeError):
display.append(string_type(item_display)) item_display = value
display.append(string_type(item_display))
return ", ".join(display) return ", ".join(display)
setattr(cls, 'get_%s_display' % self.name, get_display) setattr(cls, 'get_%s_display' % self.name, get_display)