Julian Popov
Julian Popov

Reputation: 17461

Django Templates: Form field name as variable?

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">

Upvotes: 4

Views: 6499

Answers (1)

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

Upvotes: 5

Related Questions