The {% render_field %} tag allows you to customize form fields using an HTML-like syntax. It is often easier for designers than using individual filters.
Key capabilities:
- Change input types (e.g.,
type="search"). - Add or change multiple attributes (e.g.,
rows, cols, title). - Append to existing attributes using
+= (e.g., class+="css_class_1"). - Use template variables as attribute values.
- Use double colons
:: for specific syntax requirements (like Vue.js v-bind::).
To control error and required field classes globally for render_field, use the WIDGET_ERROR_CLASS and WIDGET_REQUIRED_CLASS template variables within a {% with %} block.
{% load widget_tweaks %}
<!-- change input type -->
{% render_field form.search_query type="search" %}
<!-- add/change several attributes -->
{% render_field form.text rows="20" cols="20" title="Hello, world!" %}
<!-- append to an attribute -->
{% render_field form.title class+="css_class_1 css_class_2" %}
<!-- template variables as values -->
{% render_field form.text placeholder=form.text.label %}
<!-- double colon syntax -->
{% render_field form.search_query v-bind::class="{active:isActive}" %}
<!-- setting error/required classes via context variables -->
{% with WIDGET_ERROR_CLASS='my_error' WIDGET_REQUIRED_CLASS='my_required' %}
{% render_field form.field1 %}
{% endwith %}