I have a Question model that I am passing as a context to the template
class Question(models.Model):
possible_answer1 = models.TextField(
'Possible Answer 1',
max_length=1000,
default='none'
)
possible_answer2 = models.TextField(
'Possible Answer 2',
max_length=1000,
default='none',
blank=True
)
possible_answer3 = models.TextField(
'Possible Answer 3',
max_length=1000,
default='none',
blank=True
)
possible_answer4 = models.TextField(
'Possible Answer 4',
max_length=1000,
default='none',
blank=True
)
possible_answer5 = models.TextField(
'Possible Answer 5',
max_length=1000,
default='none',
blank=True
)
possible_answer6 = models.TextField(
'Possible Answer 6',
max_length=1000,
default='none',
blank=True
)
I can access all the answer object no problem if I use
{{ context.this_question.question.possible_answer1 }}
{{ context.this_question.question.possible_answer2 }}
.
.
{{ context.this_question.question.possible_answer6 }}
The problem is that I don't need all 6 answers to be displayed all the time so I was trying to build for loop that would only dispay what I need at a certain time based on the following thread using the with tag How to concatenate strings in django templates?1 . In the example below mylist contain four elements so I tried this
{% for x in mylist %}
{% with possible_answer='context.this_question.question.possible_answer'|add:forloop.counter %}
{{ possible_answer }}
{% endwith %}
{% endfor %}
In the hope that it would generate
{{ context.this_question.question.possible_answer1 }}
{{ context.this_question.question.possible_answer2 }}
{{ context.this_question.question.possible_answer3 }}
{{ context.this_question.question.possible_answer4 }}
and consequently display the corresponding item from the context object as if I was typing it myself but it doesn't work. Nothing is displaying
If replace forloop.counter with any string it would then display the concatened string without trying fetch the value in the context.
Anyone has an idea on how to achieve this?