I am trying to make a generic template that can be used over several pages. Its basic structure is several topics, each with its own set of questions. I’ve setup. table with radio buttons n the layout works fine.
The issue I have is getting the questions for each topic into the table. I can hardcode each set of questions, pass them via context but that means repeating the same HTML for each topic and question set. I’d like to loop through so I have an outer loop for the topic and an inner loop that populates each row with the associated questions and a radio button.
Relevant code snippets
views.py:
def leadership(request):
column_header=Column_Header.objects.all()
topic_list=Topic.objects.all()
topic = Topic.objects.get(id=1)
questions1 = topic.question_set.all()
topic = Topic.objects.get(id=2)
questions2 = topic.question_set.all()
topic = Topic.objects.get(id=3)
questions3 = topic.question_set.all()
question_list = {}
for n in range(1,len(topic_list)+1):
topic = Topic.objects.get(id=n)
questions = {}
questions["question"] = [list(topic.question_set.values_list("question"))]
question_list[ topic ] = (questions)
template.html:
<form action="" method="POST">
{% for topic in topic %}
<td colspan="7">{{ topic }}</td>
<tr>{% for question in question_list %}</tr>
<td class="question">{{ question }}</td>
{% for n in nchoices %}
{% if n == 0 %}
<td>
<input name= {{question.id}} type="radio" value={{ n }} id="{{name}}" /><lable> Not Sure</lable>
</td>
{% else %}
<td>
<input name={{question.id}} type="radio" value={{ n }} id="{{name}}" /><lable> {{n}}</lable>
</td>
{% endif %}
{% endfor %}
</tr>
{% endfor %}
{% endfor %}
If I replace
<tr>{% for question in question_list %}</tr>
with
<tr>{% for question in questions1 %}</tr>
The questions and radio buttons are laid out but that means creating separate HTML for each topic, and given the number of topics on each separate page can vary means multiple templates rather than one generic one.
Here is the question_list:
{<Topic: Risk Assessment and Planning>: {'question': [[('Conducts annual risk assessments and identifies key risks and mitigation action',), ('Identifies key risks and mitigation actions',), ('Uses risk assessment to set business continuity policy and objectives compatible with the organization’s strategic direction',)]]},
<Topic: Oversight>: {'question': [[('Provides the necessary resources for accomplishing business continuity objectives',), ('Integrates business continuity plans into business processes',), ('Communicates the importance of effective business continuity and adhering to requirements',), ('Provides direction and support to staff to drive business continuity effectiveness',)]]},
<Topic: Execution and Improvement>: {'question': [[('Conduct annual test of business continuity plans',), ('Ensures intended business continuity outcomes are achieved',), ('Promotes continual improvement by incorporating lessens learned from periodic testing or event reviews',)]]}}