HTML5 Placeholder from FormField label

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

fromdjangoimporttemplatefromdjango.formsimportFieldregister=template.Library()classPlaceholderForm(template.Node):def__init__(self,form_field):self.form_field=form_fielddefrender(self,context):html=self.form_field.resolve(context)label=html.labelreturnhtml.as_widget(attrs={'placeholder':label})@register.tagdefform_placeholder(parser,token):try:tag_name,form_field_string=token.split_contents()exceptValueError:raisetemplate.TemplateSyntaxError('{0} tag requires a single argument'.format(token.contents.split()[0]))form_field=parser.compile_filter(form_field_string)returnPlaceholderForm(form_field)