Commits

Viliam Segeda committed 519d919

Added model validation for MultiSelectField - fixing #29

Comments (0)

Files changed (1)

semanticeditor/fields.py

 from django import forms
 from django.db import models
 from django.utils.text import capfirst
+from django.utils.encoding import smart_unicode
 
 # Thanks to danielroseman from djangosnippets.org for this code!
 
         value = self._get_val_from_obj(obj)
         return self.get_db_prep_value(value)
 
+    def validate(self, value, model):
+        """
+        Validates that the input is a list or tuple.
+        """
+            
+        if not self.editable:
+            # Skip validation for non-editable fields.
+            return
+        if self._choices and value:
+            # Validate that each value in the value list is in self.choices.            
+            for val in value:
+                if not self.valid_value(val):
+                    raise ValidationError(self.error_messages['invalid_choice'] % {'value': val})
+
+        if value is None and not self.null:
+            raise exceptions.ValidationError(self.error_messages['null'])
+
+        if not self.blank and value in validators.EMPTY_VALUES:
+            raise exceptions.ValidationError(self.error_messages['blank'])
+
+    def valid_value(self, value):
+        "Check to see if the provided value is a valid choice"
+        for k, v in self.choices:
+            if isinstance(v, (list, tuple)):
+                # This is an optgroup, so look inside the group for options
+                for k2, v2 in v:
+                    if value == smart_unicode(k2):
+                        return True
+            else:
+                if value == smart_unicode(k):
+                    return True
+        return False