django---Reusable form templates

django---Reusable form templates

If your site uses the same rendering logic for forms in multiple places, you can reduce duplication by saving the form's loop in a standalone template and using the include tag to reuse it in other templates:

<form action="/contact/" method="POST">
{% include "form_snippet.html" %}
<p><input type="submit" value="Send message" /></p>
</form>
# In form_snippet.html:
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }}: {{ field }}
</div>
{% endfor %}

If the form object passed to a template has a different name within the context, you can alias it using the with tag:

<form action="/comments/add/" method="POST">
{% with comment_form as form %}
{% include "form_snippet.html" %}
{% endwith %}
<p><input type="submit" value="Submit comment" /></p>
</form>

If you find yourself doing this often, you might consider creating a custom inclusion tag.

你可能感兴趣的:(django---Reusable form templates)