Search code examples
pythondjangodjango-cms

How to get the number of form fields in a django template?


I have a django form that I can iterate over, for example, through a for loop:

{% for field in form %}
   ...
{% endfor %}

Now I'm trying to find out the total number form fields outside of the for loop. I have tried the following, but it just returns 0, even though I have 2 form fields:

{{ form|length }}

Is there any way to do this?

PS: This is in the context of django-cms 3.1.3, if this helps.


Solution

  • You'll need to explicitly count the fields, rather than just the form itself, such as:

    {{ form.fields|length }}
    

    As seen in the Django form documentation