Omar Jandali
Omar Jandali

Reputation: 824

selecting specific object from list in django template

I am working with a formset_facotry and I am having an issue trying to figure something out.

I have a list of users returned from a queryset in views.py file. I also have a list of forms that are created based on the number of objects returned from the list query. What I want to happen is that it selects the first object returned and display it before the first form that is to be displayed. Then grab the second object and displayed it right before the second form and so on... General idea behind it is the followoing:

I want it to do something like this general template:

header = 'Add record' + groupName
if message:
    print(message)
count = 0
for f in form:
    expenses[0]
    f.as_p
    count = count + 1

I want to grab a specific item based on the count within the loop:

Here is the code that I have in the template:

{% extends "base.html" %}

{% block content %}
  <h2>Add expense - {{ currentGroup.name }}</h2>
  {% if message %}
    <p>{{message}}</p>
  {% endif %}
  <form action="." method="POST">
    {% csrf_token %}
    {{ form.management_form }}
    {% with count=0 %}
      {% for f in form %}
        {% for expense in expenses %}
          <p>{{ expense.user.username }}</p>
        {% endfor %}
        {{ f.as_p }}
      {% endfor %}
    {% endwith %}
    <input type="submit" name="submit" value="submit">
  </form>
{% endblock %}

can someone help me figure out how to iterate and specify a certain object within an object set in the html template

Upvotes: 0

Views: 2335

Answers (3)

Gavin Clark
Gavin Clark

Reputation: 299

Sounds like you're looking for python's zip() function, which will join two lists to allow you to iterate through them together. You'll need to zip the lists together in the view and then you can iterate over the new list in the template.

In the view:

forms_and_users = zip(forms_list, users_list)
# Add forms_and_users to template context

In the template

{% for form, user in forms_and_users %}
    {{ user }}
    {{ form }}
{% endfor %}

Upvotes: 0

Neeraj Kumar
Neeraj Kumar

Reputation: 3941

I think below code will work for you with template loops

{% for f in form %}
   {% for expense in expenses %}
       {% if forloop.parentloop.counter == forloop.counter %}
          <p>{{ expense.user.username }}</p>
       {% endif %}
   {% endfor %}
   {{ f.as_p }}
{% endfor %}

Upvotes: 1

user2390182
user2390182

Reputation: 73470

You can access forloop.counter which is a 1-based counter:

{% for expense in expenses %}
  {% if forloop.counter == 25 %}  # this is the 25th, not 26th item
      do stuff
  {% endif %}
{% endfor %}

Upvotes: 0

Related Questions