1

i need a small help.. i am looping over objects which are in db and rendering all objects to template, so far so good. but what i want is that every rendered html name field should have different name so that i can refer to all of them latter. my code is this:

{% for p in products %}
      <input type="number" name="name1" value="{{p.arg1}}" size="12"/>
          <input type="number" name="name2" value="{{p-arg2}}" size="12"/>
{% endfor %}

but if i have 4 objects in DB, then i will have 8 rendered input fields in template, but all of them will have the "name" value as name1 and name2, is it possible to create 8 different names dynamically so that i can refer to all of them in my view again...

thanks

1 Answer 1

2

Use the forloop.counter variable

{% for p in products %}
    <input type="number" name="name-{{forloop.counter}}-arg1" value="{{p.arg1}}" size="12"/>
    <input type="number" name="name-{{forloop.counter}}-arg2" value="{{p.arg2}}" size="12"/>
{% endfor %}

The forloop.counter is 1-indexed. There is also the forloop.counter0 for indices starting with 0.

Are you sure though that django formsets isn't what you need?

Sign up to request clarification or add additional context in comments.

1 Comment

perfect solution, i didnot know that. now i know. great! many thanks.. django formsets are actually cleaner solution. this is also working anyway.. :). thank u again

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.