Enables you to store a comma-delimited string in a field, returning a corresponding list
From Django Import forms
From django.db import Models
From Django.utils.text import Capfirst
From Django.core Import exceptions
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
Class Multiselectfield (models. Field):
__metaclass__ = models. Subfieldbase
def get_internal_type (self):
Return "Charfield"
def get_choices_default (self):
Return Self.get_choices (Include_blank=false)
def _get_field_display (self, FIELD):
Value = GetAttr (self, field.attname)
Choicedict = Dict (field.choices)
def formfield (self, **kwargs):
# don ' t call Super, as that overrides default widget if it has choices
Defaults = {' Required ': not Self.blank, ' label ': Capfirst (Self.verbose_name),
' Help_text ': self.help_text, ' Choices ': Self.choices}
If Self.has_default ():
defaults[' initial '] = Self.get_default ()
Defaults.update (Kwargs)
Return Multiselectformfield (**defaults)
def get_prep_value (self, value):
return value
def get_db_prep_value (self, value, Connection=none, Prepared=false):
If Isinstance (value, basestring):
return value
Elif isinstance (value, list):
Return ",". Join (value)
def to_python (self, value):
If value is not None:
return value if Isinstance (value, list) Else Value.split (', ')
Return ""
def contribute_to_class (self, CLS, name):
Super (Multiselectfield, self). Contribute_to_class (CLS, name)
if Self.choices:
func = lambda self, fieldname = Name, Choicedict = Dict (self.choices): ",". Join ([Choicedict.get (value, value) for value in GetAttr (self, fieldname)])
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 (int (opt_select) not In arr_choices): # The Int () is to comparing with integer choices
&nbs p; raise exceptions. ValidationError (self.error_messages[' invalid_choice ']% value)
return
def get_choices_selected (self, arr_choices= '):
If not arr_choices:
Return False
list = []
For choice_selected in Arr_choices:
List.append (Choice_selected[0])
Return list
def value_to_string (self, obj):
Value = Self._get_val_from_obj (obj)
return Self.get_db_prep_value (value)