我是 django 新手,我的项目设置方式与教程“polls”项目完全相同。 当我通过按钮提交选项时,我试图让页面不刷新或重定向到另一个 View 。
这是我的detail.html:
(...)
<div class="cardq mt15">
<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
<!-- New Question -->
<div class="cardq__qu">
<i class="far fa-question-circle"></i>
<!--<p name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br>
</p>-->
<input type="submit" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> </div>
{% endfor %}
(...)
我的views.py中有这个:
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
我基本上想要的是不重定向到 results.html 并在detail.html 上显示结果而不刷新页面,与具有投票按钮的页面相同。它已经在同一页面上准确地显示了民意调查结果,但如果我单击其中一个按钮,它会强制重定向到结果页面。
最佳答案
尝试在 django 中使用 ajax。 This是一个很好的起点。
关于python - 如果不使用 Django 刷新页面,则无法使用提交按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60214349/