diff --git a/src/codeschool/lms/fields/models.py b/src/codeschool/lms/fields/models.py index 3692f20..3f77032 100644 --- a/src/codeschool/lms/fields/models.py +++ b/src/codeschool/lms/fields/models.py @@ -1,8 +1,5 @@ from django.utils.translation import ugettext_lazy as _ - from codeschool import models -from django.core.exceptions import ValidationError -from django.core.validators import URLValidator class Field(models.Model): """ @@ -43,25 +40,9 @@ class FieldValue(models.Model): field = models.ForeignKey('Field') user = models.ForeignKey('users.User') content = models.CharField( - max_length = 200, + max_length = 200 ) - def clean(self): - # Custom validation for generic type field - if self.field.field_type == Field.TYPE_INT: - if not isinstance(self.content, int): - raise ValidationError(_('Content must be a Int')) - elif self.field.field_type == Field.TYPE_FLOAT: - if not isinstance(self.content, float): - raise ValidationError(_('Content must be a float')) - elif self.field.field_type == Field.TYPE_URL: - url_validator = URLValidator() - try: - url_validator(self.content) - except: - ValidationError(_('Content must be a URL')) - - class Meta: unique_together = [('field', 'user')] diff --git a/src/codeschool/lms/fields/serializers.py b/src/codeschool/lms/fields/serializers.py index 5655bb9..15bbcff 100644 --- a/src/codeschool/lms/fields/serializers.py +++ b/src/codeschool/lms/fields/serializers.py @@ -1,5 +1,7 @@ from rest_framework import serializers - +from django.utils.translation import ugettext_lazy as _ +from django.core.exceptions import ValidationError +from django.core.validators import URLValidator from . import models @@ -19,6 +21,39 @@ class FieldValueSerializer(serializers.HyperlinkedModelSerializer): Serialize Field Value objects. """ + def validate(self, data): + # Custom validation for generic type field + field = data['field'] + value = data['content'] + + if field.field_type == models.Field.TYPE_INT: + try: + parsed_value = int(value) + except: + raise ValidationError( + _('%(value)s is not an Integer'), + params={'value': value}, + ) + elif field.field_type == models.Field.TYPE_FLOAT: + try: + parsed_value = float(value) + except: + raise ValidationError( + _('%(value)s is not an Float'), + params={'value': value}, + ) + elif field.field_type == models.Field.TYPE_URL: + url_validator = URLValidator() + try: + url_validator(value) + except: + raise ValidationError( + _('%(value)s is not an URL'), + params={'value': value}, + ) + + return data + class Meta: model = models.FieldValue fields = (