4

How can I make this loop to print form fields where XXXXXXXX is the value of ticket.id?

{% for ticket in zone.tickets %}
    {{ ticket.id }}: {{ form.ticket_count_XXXXXXXX }}
{% endfor %}

So the output to be something like this...

1: <input ... name="ticket_count_1">
10: <input ... name="ticket_count_10">
12: <input ... name="ticket_count_12">
3: <input ... name="ticket_count_3">
1

1 Answer 1

5

You can't pass arguments in the django template, so no.

You'd need to implement a template tag (more of a pain) or filter, or make the association from ticket to formfield in your view (what I would recommend).

Since I don't actually know the relationship between ticket and your form fields, I can't tell what the best method is, but this would 'just work' based on the info you've provided.

# view
form = MyForm()
for ticket in zone.tickets:
    ticket.form_field = form['ticket_count_' + str(ticket.id)]

# template
{% for ticket in zone.tickets %}
    {{ ticket.id }} : {{ ticket.form_field }}
{% endfor %}
Sign up to request clarification or add additional context in comments.

4 Comments

This looks like it will work "#ticket['form_field'] = purchaseForm.fields['ticket_' + str(ticket['id'])];" but insted of field HTML I get "<django.forms.fields.IntegerField object at 0x017938D0>"
oops, yeah, I meant to say getattr(form, 'attr')
Yeah, don't do form.fields['field']-- that will literally get you the field object, not the BoundField object that prints as a widget
There we go, try: ticket.form_field = form['ticket_count_' + str(ticket.id)], that will get you the BoundField you need

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.