Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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">
like image 451
Julian Popov Avatar asked Oct 15 '25 06:10

Julian Popov


1 Answers

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 %}
like image 146
Yuji 'Tomita' Tomita Avatar answered Oct 16 '25 20:10

Yuji 'Tomita' Tomita



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!