Dynamically add css-classes to formfields

 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# Forms.py:

from django import forms
class MyForm(forms.Form):
    field1 = forms.IntegerField()
    field2 = forms.IntegerField()
    
    def __init__(self, *args, **kwargs):
        highlight_field = kwargs.pop('highlight')    #pass the fieldname-to-highlight as kwarg
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields[highlight_field].css = "highlight"

    # first part done. Now you have the css-attribute attached to your field.


# templatetags\form_manipulation_filters.py:
"""
We need an own template-filter to access the css-attribute. We can't just use
   {{ field.css }} in the template, since {{ field
"""
from django.conf import settings
from django import template

register = template.Library()

@register.filter(name='css')
def css(field):
    try:
        css = field.form.fields[field.name].css
        return css
    except AttributeError:
        return settings.TEMPLATE_STRING_IF_INVALID
css.is_safe = True

# form_snippet.html:
"""
This snippet can be included inside a <form> like:
    <form method="POST" action="">
	{% with form=myform %}
	{% include "form_snippet.html" %}
	{% endwith %}
	<input type="submit" value="Submit"></td>
    </form>
"""
{% load form_manipulation_filters %}
{% csrf_token %}

{{ form.non_field_errors }}

{% for field in form.hidden_fields %}
    <div class="formfield">
        {{ field }}
    </div>
{% endfor %}

{% for field in form.visible_fields %}
    <div class="formfield {{ field|css }}">
        {{ field }}
        {{ field.help_text }}
	{{ field.errors }}   {# errors are after the field #}
    </div>
{% endfor %}

More like this

  1. Filter by taggit tags in the admin (Django 1.4) by albertorcf 1 year, 7 months ago
  2. Class Feeds DRY TemplateTag by gmandx 3 years, 11 months ago
  3. Custom CSS class in Form with template tag filter by kegan 4 years, 10 months ago
  4. Render dynamically assigned fields in a template by rubic 7 years, 1 month ago
  5. tag: render form field by crucialfelix2 4 years, 4 months ago

Comments

(Forgotten your password?)