I am writing a site on Django, the purpose of this site is to create a test to assess students' knowledge
I need help with outputting options for answers to a question
I keep the questions in a list and the answer options in a nested list for example:
questions = [ "question1","question2","question3"]
answers = [[ "answer1","answer2",answer3 ],["answer1","answer2",answer3,answer4 ] ,
["answer1","answer2",answer3 ]]`
and I need this data to be displayed in the following format:
question1
answer1
answer2
answer3
question2
answer1
answer2
answer3
answer4
question3
answer1
answer2
answer3
here is my code, it does not work very correctly, I know, I have not yet figured out how to implement it in Django tags
{% for question in questions %}
<p>{{question}}</p>
<ul>
{% for answer in answers %}
{% for current in answer %}
<li><input type="radio" id="option{{ forloop.parentloop.counter }}_{{ forloop.counter }}" name="answer{{ forloop.parentloop.counter }}" value="{{ current }}">{{ current }}</li>
{% endfor %}
{% endfor %}
</ul>
{% endfor %}
Perform the joining in the view:
def my_view(request):
questions = ['question1', 'question2', 'question3']
answers = [
['answer11', 'answer12', 'answer13'],
['answer21', 'answer22', 'answer23', 'answer24'],
['answer31', 'answer32', 'answer33'],
]
return render(request, 'some_template.html', {'qas': zip(questions, answers)})
and in the template work with:
{% for question, answers in qas %}
<p>{{question}}</p>
<ul>
{% for answer in answers %}
<li><input type="radio" id="option{{ forloop.parentloop.counter }}_{{ forloop.counter }}" name="answer{{ forloop.parentloop.counter }}" value="{{ current }}">{{ current }}</li>
{% endfor %}
</ul>
{% endfor %}
That being said, what you do is primitive obsession [refactoring.guru]: expressing data in terms of lists, strings, etc. If data has a certain structure, it makes more sense to define a dedicated class for it, and add logic to it. For example to render the id=""
for the option, and logic to parse back data.