Django基于类的视图开发测验应用:逐题切换功能实现方案咨询
两种实现方案:前端JS或后端Django视图
你有两种可行的实现方式,具体选哪种取决于你的需求:
一、纯前端JavaScript实现(无后端请求)
如果你的需求只是逐题查看、不需要保存答题进度或答案到数据库,这种方案更高效,用户体验更流畅(无页面刷新)。
实现思路:
- 在Django模板中一次性渲染所有问题,但默认只显示第一题,其余隐藏。
- 用JavaScript跟踪当前显示的题目索引,点击「下一页」按钮时切换到下一题,隐藏当前题。
示例代码:
Django模板(比如quiz.html):
<div class="question-container"> {% for question in questions %} <div class="question-item" {% if not forloop.first %}style="display: none;"{% endif %}> <h3>{{ question.text }}</h3> <!-- 选项部分 --> {% for option in question.options.all %} <div> <input type="radio" name="answer_{{ question.id }}" value="{{ option.id }}"> <label>{{ option.text }}</label> </div> {% endfor %} </div> {% endfor %} </div> <button id="next-btn">下一页</button> <script> const questionItems = document.querySelectorAll('.question-item'); const nextBtn = document.getElementById('next-btn'); let currentIndex = 0; nextBtn.addEventListener('click', () => { // 隐藏当前题 questionItems[currentIndex].style.display = 'none'; // 切换到下一题,如果是最后一题可以禁用按钮 currentIndex++; if (currentIndex < questionItems.length) { questionItems[currentIndex].style.display = 'block'; } else { nextBtn.disabled = true; nextBtn.textContent = '已完成'; } }); </script>
二、后端Django类视图实现
如果需要保存用户的答题进度、答案到数据库,或者题目数量过多不想一次性加载,这种方案更合适,所有状态由后端控制。
实现思路:
- 用Django类视图(比如
DetailView或自定义TemplateView)接收当前题目的ID或索引参数。 - 点击「下一页」按钮时,向后端发送请求,获取下一题的数据并渲染新页面。
示例代码:
视图文件(views.py):
from django.views.generic import DetailView from .models import Question class QuestionDetailView(DetailView): model = Question template_name = 'question_detail.html' context_object_name = 'current_question' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # 获取当前题目的下一题(假设题目按id排序) next_question = Question.objects.filter(id__gt=self.object.id).first() context['next_question'] = next_question return context
URL配置(urls.py):
from django.urls import path from .views import QuestionDetailView urlpatterns = [ path('question/<int:pk>/', QuestionDetailView.as_view(), name='question_detail'), ]
模板(question_detail.html):
<div class="question"> <h3>{{ current_question.text }}</h3> {% for option in current_question.options.all %} <div> <input type="radio" name="answer" value="{{ option.id }}"> <label>{{ option.text }}</label> </div> {% endfor %} </div> {% if next_question %} <a href="{% url 'question_detail' next_question.id %}" class="btn">下一页</a> {% else %} <p>测验已完成</p> {% endif %}
选择建议
- 若只是简单的逐题浏览,选JS方案,体验更好且减少服务器压力。
- 若需要持久化答题数据、权限控制或动态加载题目,选后端方案,更安全可控。
内容的提问来源于stack exchange,提问作者vijay jagtap
相关产品推荐
相关产品推荐

