views:

83

answers:

1

Hi,

I have a list of soccer matches for which I'd like to display forms. The list comes from a remote source.

matches = ["A vs. B", "C vs. D", "E vs, F"]
matchFormset = formset_factory(MatchForm,extra=len(matches))
formset = MatchFormset()

On the template side, I would like to display the formset with the according title (i.e. "A vs. B").

{% for form in formset.forms %}
    <fieldset>
        <legend>{{TITLE}}</legend>
        {{form.team1}} : {{form.team2}}
    </fieldset>
{% endfor %}

Now how do I get TITLE to contain the right title for the current form? Or asked in a different way: how do I iterate over matches with the same index as the iteration over formset.forms?

Thanks for your input!

+2  A: 

I believe that in the Django template language there is no built-in filter for indexing, but there is one for slicing (slice) -- and therefore I think that, in a pinch, you could use a 1-item slice (with forloop.counter0:forloop.counter) and .first on it to extract the value you want.

Of course it would be easier to do it with some cooperation from the Python side -- you could just have a context variable forms_and_matches set to zip(formset.forms, matches) in the Python code, and, in the template, {% for form, match in forms_and_matches %} to get at both items simply and readably (assuming Django 1.0 or better throughout this answer, of course).

Alex Martelli
Thank you so much, Alex. Zipping is such a beautiful and simple solution!
Jannis