diff --git a/apps/documents/models.py b/apps/documents/models.py index 993a0b60f3..536153877d 100644 --- a/apps/documents/models.py +++ b/apps/documents/models.py @@ -1,6 +1,7 @@ import os import tempfile import hashlib +from ast import literal_eval from django.db import models from django.utils.translation import ugettext_lazy as _ @@ -8,6 +9,7 @@ from django.contrib.auth.models import User from django.contrib.contenttypes import generic from django.contrib.comments.models import Comment from django.conf import settings +from django.core.exceptions import ValidationError from taggit.managers import TaggableManager from dynamic_search.api import register @@ -295,6 +297,27 @@ class DocumentPage(models.Model): return ('document_page_view', [self.pk]) +class ArgumentsValidator(object): + message = _(u'Enter a valid value.') + code = 'invalid' + + def __init__(self, message=None, code=None): + if message is not None: + self.message = message + if code is not None: + self.code = code + + def __call__(self, value): + """ + Validates that the input evaluates correctly. + """ + value = value.strip() + try: + literal_eval(value) + except (ValueError, SyntaxError): + raise ValidationError(self.message, code=self.code) + + class DocumentPageTransformation(models.Model): """ Model that stores the transformation and transformation arguments @@ -303,7 +326,7 @@ class DocumentPageTransformation(models.Model): document_page = models.ForeignKey(DocumentPage, verbose_name=_(u'document page')) order = models.PositiveIntegerField(default=0, blank=True, null=True, verbose_name=_(u'order'), db_index=True) transformation = models.CharField(choices=get_available_transformations_choices(), max_length=128, verbose_name=_(u'transformation')) - arguments = models.TextField(blank=True, null=True, verbose_name=_(u'arguments'), help_text=_(u'Use dictionaries to indentify arguments, example: {\'degrees\':90}')) + arguments = models.TextField(blank=True, null=True, verbose_name=_(u'arguments'), help_text=_(u'Use dictionaries to indentify arguments, example: {\'degrees\':90}'), validators=[ArgumentsValidator()]) objects = DocumentPageTransformationManager()