/
goodfields.py
61 lines (46 loc) · 1.82 KB
/
goodfields.py
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
from django import template
from django.conf import settings
from django.template.loader import render_to_string
validate = (hasattr(settings, 'GOODFIELD_VALIDATION') and settings.GOODFIELD_VALIDATION)
register = template.Library()
class GoodfieldNode(template.Node):
def __init__(self, field, field_type, label=None, validation=None):
self.field = template.Variable(field)
self.field_type = field_type.strip('"')
self.label = label.strip('"') if label else None
self.validation = validation
def render(self, context):
field = self.field.resolve(context)
f = field.form
initial = field.data if f.data else f.initial.get(field.name, '')
template = "goodfields/fields/%s.html" % self.field_type
return render_to_string(template, {
'field': field,
'initial': initial,
'label': self.label,
'validation': self.validation,
'validate': validate,
})
@register.tag
def goodfield(parser, token):
"""Render good form fields."""
bits = token.split_contents()
tag_name = bits.pop(0)
if len(bits) < 2:
raise template.TemplateSyntaxError(
u"'%s' tag requires at least a field and field type." % tag_name
)
field = bits.pop(0)
field_type = bits.pop(0)
bits, kwargs = iter(bits), { 'validation': {} }
for bit in bits:
if bit == 'label':
kwargs['label'] = bits.next()
if bit == 'email':
kwargs['validation']['email'] = True
if bit == 'pattern':
kwargs['validation']['pattern'] = {
're': bits.next().strip('"'),
'message': bits.next().strip('"'),
}
return GoodfieldNode(field, field_type, **kwargs)