0

I have a list called forms which I am passing to a Django (1.5.1) template:

<div class="content">
{% if forms %}
  <form method="POST" enctype="multipart/form-data" class="survey">
   <div class="image">
     {{ forms.0.as_p }}
    </div>
    <div class="questions">
    {% for form in forms %}
      {{ form.as_p }}
    </div>
    {% endfor %}
    <input type="submit" value="Submit Survey"/>
  </form>
{% endif %}
<div class="content">

I want to do two separate things:

  1. Put the first element of the forms list inside a div tag with class="image".
  2. Put the rest of the elements inside a div tag with class="questions"

There are SO questions about how to reference list items by index inside a django template, but forms.0.as_p doesn't render anything for me. Also, how to get a sublist of items from forms (something like forms[1:])?

EDIT

While the question has been correctly answered below, I'll add another way of doing it using slice.

<form method="POST" enctype="multipart/form-data" class="survey">
 <div class="image">
  {{ forms.0.as_p }}
 </div>
 <div class="questions">
  {% with myforms=forms|slice:"1:"%}
   {% for form in myforms %}
      {{ form.as_p }}
   {% endfor %}
  {% endwith %}
 </div>
Community
  • 1
  • 1
rivu
  • 2,004
  • 2
  • 29
  • 45

1 Answers1

1

Use the forloop.first variable to determine the first form in the list:

{% for form in forms %}
<div class="{{ forloop.first|yesno:'image,question' }}">
   {{ form.as_p }}
</div>
{% endfor %}

P.S. You don't need it for this case but to get the sublist in the template you can use the slice template filter.

catavaran
  • 44,703
  • 8
  • 98
  • 85
  • It is creating an empty div element called image. All elements of the "forms" list is appearing with the div element "question" – rivu Mar 23 '15 at 00:54
  • @rivu You must have an empty form at index 0. How do you construct forms list? – Selcuk Mar 23 '15 at 00:56
  • This means that the first element of the `forms` list is empty. And I suspect this is why it doesn't render anything with the `{{ forms.0.as_p }}` tag. How do you create it? – catavaran Mar 23 '15 at 00:56
  • yes you are right, the first element f the list is empty. I was improvising on django-crowdsourcing for my purpose. I'll check again. thanks. – rivu Mar 23 '15 at 01:09