# 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 %}
Comments