Sunday, April 17, 2011

[Django Templates] 'for' loop through form fields and excluding one of the fields with 'if'.

Hi, The problem I'm struggling with is as follows:

I have:

{% for field in form %}
    {{ field }}
{% end for %}

What I want is to put an 'if' statement to exclude a field which .label or whatever is provided. Like:

{% for field in form%}
    {% if field == title %}
    {% else %}
        {{ field }}
    {% endif %}
{% endfor %}

Is it possible? I have to many fields to write them one by one and only one or two to exclude.

Thank you for any tips.

BR, Czlowiekwidmo.

From stackoverflow
  • Yes, this should be possible:

    {% for field in form %}
        {% ifnotequal field.label title %}
            {{ field }}
        {% endifnotequal %}
    {% endfor %}
    

    Django's template tags offer ifequal and ifnotequal variants, and you can test the field.label against either a context variable, or a string.

  • You might be a lot happier creating a subclass of the form, excluding the offending field. See http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#form-inheritance

    class SmallerForm( MyForm ):
        class Meta(MyForm.Meta):
            exclude = [ title ]
    
    muhuk : +1. This is a better solution than {% if %}. Also I'd try using as_* rendering methods on form.

0 comments:

Post a Comment