django-goodfields / goodfields / templatetags / goodfields.py

from django import template
from django.conf import settings
from django.template.loader import render_to_string

validate = (hasattr(settings, 'GOODFIELDS_VALIDATE') and settings.GOODFIELDS_VALIDATE)
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)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.