Display additional data, iterating over a Django set

I have a list of football matches for which I would 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 a set of forms with an appropriate heading (ie, “A vs. B”).

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

Now how do I get a TITLE to contain the correct title for the current form? Or it is set differently: how do I matches over matches with the same index as iterating over formset.forms ?

Thanks for your input!

+4
source share
2 answers

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

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

+6
source

This is a complement to Alex's answer.

I read some comments after my comment on Alex answered and found that it is important to get a control form (basically a meta form with information about how many forms are in the form set) in your template so that your submitted data is considered as a format, not just a bunch of forms. The documentation is here .

Only two ways that I know to get this in your template:

  • Submit the form set in addition to any data structure you created, and then visualize the control form with {{my_formset.management_form}}
  • Mark the control form in your view and submit it as an element to your template

Of course, if you use the first Alex method, a set of forms is already available so that you can directly add a control form.

+2
source

Source: https://habr.com/ru/post/1312013/


All Articles