Login

Django forms add placeholder from help text template tag

Author:
Ahmad.Dukhan
Posted:
May 17, 2014
Language:
Python
Version:
1.6
Tags:
template tag forms help_text Django placeholder
Score:
0 (after 0 ratings)

This snippet will change the field to include the placeholder in the field using the help_text attribute from the model or the form

 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
###################################################
#
#   Usage: 
#       {% load help_text_as_placeholder %}
#       form.field|help_text_as_placeholder
#       OR
#       field|help_text_as_placeholder
###################################################

from django import template
from django.utils.safestring import mark_safe
register = template.Library()

IGNORE_FIELDS = ['<textarea', '<select']


@register.filter("help_text_as_placeholder")
def help_text_as_placeholder(field):
    html = field.as_widget()

    return _get_field_with_placeholder(field, html)


def _get_field_with_placeholder(field, html):
    for ignored_field in IGNORE_FIELDS:
        if (ignored_field not in html):
            html_parts = html.split("/>")
            placeholder = field.help_text or field.name.title()
            html_parts.append('placeholder="{}"'.format(placeholder))
            html_parts.append(' />')
        else:
            return html
    return mark_safe(''.join(html_parts))

More like this

  1. HTML5 Placeholder from FormField label by Hillshum 2 years, 7 months ago
  2. Generic model filter from request GET data by genbit 3 years, 10 months ago
  3. Dynamic Django form by rufman 7 years, 1 month ago
  4. Modify properties on fields inherited from an abstract superclass by andybak 11 months ago
  5. Django newforms ExtJS JSON Encoder by davidblewett 6 years, 11 months ago

Comments

Please login first before commenting.