summaryrefslogtreecommitdiffstats
path: root/utils.py
blob: fbec4c9b7fd32620ebe53c2b82c693ccde1e112e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from functools import wraps
from flask import request, render_template
from wtforms import Field, ValidationError
from widgets import Static

# using http://flask.pocoo.org/docs/patterns/viewdecorators/
def templated(template=None):
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            template_name = template
            if template_name is None:
                template_name = request.endpoint \
                    .replace('.', '/') + '.html'
            ctx = f(*args, **kwargs)
            if ctx is None:
                ctx = {}
            elif not isinstance(ctx, dict):
                return ctx
            return render_template(template_name, **ctx)
        return decorated_function
    return decorator

class Unique(object):
    """ validator that checks field uniqueness """
    def __init__(self, model, field, message=None):
        self.model = model
        self.field = field
        if not message:
            message = u'This element already exists.'
        self.message = message

    def __call__(self, form, field):         
        try:
            self.model.get(self.field == field.data)
            raise ValidationError(self.message)
        except self.model.DoesNotExist:
            pass


class ReadonlyField(Field):
    widget = Static()

    def process_formdata(self, _):
        pass