0

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

3 Answers 3

1

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 %}
Sign up to request clarification or add additional context in comments.

1 Comment

It worked perfectly. that you so much for that. I really appreciate it @neerajkumar
0

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 %}

Comments

0

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 %}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.