Login

Django forms add placeholder from help text template tag

Author:
Ahmad.Dukhan
Posted:
May 17, 2014
Language:
Python
Version:
1.6
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. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.