Django如何实现逐题展示?解决一次性加载全部问题的需求
嘿,我来帮你搞定这个逐题展示的需求!你现在的代码是一次性把所有题目都渲染出来了,要改成答完一道再显示下一道,有两种实用的思路,我给你拆解清楚:
方案一:后端控制(带进度保存)
这个方法用Django的session记录用户当前的答题进度,适合需要保留进度的场景(比如刷新页面后还能回到当前题目),而且可以在后端逐题处理用户的答案。
修改views.py
from django.shortcuts import render, redirect from .models import Questions def qpage(request): # 按题目ID排序,确保顺序正确 all_questions = Questions.objects.order_by('id') total_questions = all_questions.count() # 从session获取当前题目索引,默认从第1题(索引0)开始 current_idx = request.session.get('current_question_idx', 0) if request.method == 'POST': # 这里可以处理用户提交的答案,比如保存到数据库或session user_answer = request.POST.get('ans') # 示例:把答案存在session,用题目ID作为键 request.session[f'answer_{all_questions[current_idx].id}'] = user_answer # 判断是否还有下一题 if current_idx < total_questions - 1: # 跳转到下一题,更新session里的索引 current_idx += 1 request.session['current_question_idx'] = current_idx else: # 所有题目答完,清空进度session,跳转到完成页(或显示提示) del request.session['current_question_idx'] return render(request, 'data/complete.html') # 你需要创建这个模板 # 获取当前要显示的题目 current_question = all_questions[current_idx] return render(request, 'data/quit.html', { 'question': current_question, 'current_num': current_idx + 1, # 显示给用户的序号(从1开始) 'total': total_questions })
修改quit.html模板
现在模板只需要渲染当前的一道题,不用循环所有题目了:
<form class="form" method="post" action=""> {% csrf_token %} <h3>{{ current_num }}. {{ question.question }}</h3> <input type="text" name="ans" id="q_ans" placeholder="输入你的答案"> {% if current_num < total %} <button type="submit">Next</button> {% else %} <button type="submit">Submit All</button> {% endif %} </form>
方案二:前端JS控制(快速实现)
如果不需要后端保存进度,用纯前端JS就能搞定——页面加载时隐藏所有题目,只显示第一题,用户点击「Next」按钮时切换到下一题,最后再一次性提交所有答案。
保留原views.py(只需确保题目按ID排序)
def qpage(request): questions = Questions.objects.order_by('id') return render(request, 'data/quit.html', {'questions': questions})
修改quit.html模板,加入JS逻辑
<form class="form" method="post" action=""> {% csrf_token %} {% for q in questions %} <!-- 除了第一题,其他题目默认隐藏 --> <div class="question-block" {% if not forloop.first %}style="display: none;"{% endif %}> <h3>{{ q.id }}. {{ q.question }}</h3> <input type="text" name="ans_{{ q.id }}" id="q{{ q.id }}a"> </div> {% endfor %} <button type="button" id="next-btn">Next</button> <button type="submit" id="submit-btn" style="display: none;">Submit All</button> </form> <script> const questionBlocks = document.querySelectorAll('.question-block'); const nextBtn = document.getElementById('next-btn'); const submitBtn = document.getElementById('submit-btn'); let currentIndex = 0; nextBtn.addEventListener('click', () => { // 隐藏当前题目 questionBlocks[currentIndex].style.display = 'none'; currentIndex++; // 显示下一题,或者切换到提交按钮 if (currentIndex < questionBlocks.length) { questionBlocks[currentIndex].style.display = 'block'; } else { nextBtn.style.display = 'none'; submitBtn.style.display = 'block'; } }); </script>
两种方案的小提示
- 后端方案适合需要验证每一题答案、保存答题记录的场景,进度不会因为页面刷新丢失。
- 前端方案更轻量化,快速实现,但刷新页面会回到第一题,所有答案是最后一次性提交的。
内容的提问来源于stack exchange,提问作者Rahul Saini
相关产品推荐
相关产品推荐

