Search code examples
djangoformsdjango-templatesrenderingform-fields

Exclude some form fields while rendering in django-templates


I have a code block in order to render the form fields in my template such that

{% for field in form.visible_fields %}
<div class="field_container">
    <div class="field_label question">
    {% field.label_tag  %}
    </div>
    <div class="field_field">
    {{ field}}
    </div>
{% endfor %}
{% for field in form.hidden_fields %}
{{ field }}
{% endfor %}

Is there any way to exclude some certain form fields by specifying their names ?

Thanks


Solution

  • Is this a modelForm, or a regular form?

    If it is a modelForm

    you can use the exclude() or fields() list on the Meta class on the modelForm.

    https://docs.djangoproject.com/en/1.3/topics/forms/modelforms/#using-a-subset-of-fields-on-the-form

    If it is a regular form:

    If you know the names of the fields you can put in a simple if check for those fields and if it isn't one of them you print your html, if it matches it will not put the html. Not an ideal solution.

    The better approach would be to create a different form field that only has the fields that you want and use that one.