Skip to content

Commit

Permalink
Merge pull request #16 from MES-codeSSchool/create_validations
Browse files Browse the repository at this point in the history
Create validations
  • Loading branch information
Gabiras12 authored Oct 31, 2017
2 parents 6d3db34 + 25d34f8 commit f059e78
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 21 deletions.
21 changes: 1 addition & 20 deletions src/codeschool/lms/fields/models.py
Original file line number Diff line number Diff line change
@@ -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):
"""
Expand Down Expand Up @@ -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')]

Expand Down
37 changes: 36 additions & 1 deletion src/codeschool/lms/fields/serializers.py
Original file line number Diff line number Diff line change
@@ -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


Expand All @@ -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 = (
Expand Down

0 comments on commit f059e78

Please sign in to comment.