Login

HTML5 Placeholder from FormField label

Author:
Hillshum
Posted:
October 24, 2012
Language:
Python
Version:
Not specified
Score:
0 (after 0 ratings)

This allows for easy generation of HTML5 placeholders based on a form_field's label. Use like so:

{% form_placeholder form.username %}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from django import template
from django.forms import Field

register = template.Library()

class PlaceholderForm(template.Node):
    def __init__(self, form_field):
        self.form_field =  form_field
    
    def render(self, context):
        html = self.form_field.resolve(context)
        label = html.label
        return html.as_widget(attrs={'placeholder':label})


@register.tag
def form_placeholder(parser, token):
    try:
        tag_name, form_field_string = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError('{0} tag requires a single argument'.format( token.contents.split()[0]))
    form_field = parser.compile_filter(form_field_string)
    return PlaceholderForm(form_field)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.