Django]如何在提交表单后显示消息(正确或不正确),而不刷新页面



我有一个测试页面,它使用"checkans"函数检查用户的答案是否正确。如果答案正确,我想返回"正确"信息;如果答案不正确,我希望返回"不正确"信息。现在我可以"有点"做了,但不是我想要的。现在,它在重定向到一个全新的页面后返回消息,问题框和其他一切都完全消失了,只有消息。

我希望在提交答案后,消息显示在同一个原始问题页面上,问题框下或问题框内的某个位置,而不重定向到另一个页面或刷新页面。我不知道怎么做。

这是我的观点:

class QuizView(generic.ListView):
template_name = 'geniusdennis/quiz.html'
queryset = Spanish.objects.all()
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# grab the max id in the database       
max_id = Spanish.objects.order_by('-id')[0].id
random_id = random.randint(1, max_id + 1)
random_spanish_question = Spanish.objects.filter(id__gte=random_id)[0]
context['random_spanish_question'] = random_spanish_question
return context

这是我检查答案的功能:

def checkans(request, spanish_id):
random_spanish_question = get_object_or_404(Spanish, pk=spanish_id)
query = request.GET.get('ans')
coreng = random_spanish_question.english_set.get()
if query == str(coreng):
return render(request, 'geniusdennis/quiz.html',{
'message': "Correct!",
})
else:
return render(request, 'geniusdennis/quiz.html', {
'message': "Incorrect.",
'correct_answer': "The correct answer is " + str(coreng),
})

这是我的HTML页面:

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'geniusdennis/style.css' %}">
{% if random_spanish_question %}
<div class="flexcontainer" style="justify-content: center;">
<div class="sectiontitle">Quiz time
</div>
<div class="question_card">
<div class="question_word">{{ random_spanish_question }}</div>
<form action="/checkans/{{random_spanish_question.id}}/" method="get">{% csrf_token %}
<label for="one_answers">Answer:</label>
<input type="text" name="one_answers"/>
<input type="submit" value="Submit"/>
</form>
<input type="submit" value="Skip"/>
</div>
</div>
{% else %}
{% if message %}
<div class="message">
{{ message }}
</div>
<div class="one_answers">
{{ correct_answer }}
</div>
{% endif %}
{% endif %}

您需要的是ajax,因此您需要一些js代码。

<scrip src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$('form').on('submit', function(e) { // or you can get the form by id if you set it
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
$.ajax({
type: 'GET',
url: url,
data: form.serialize(), // serializes the forms elements.
success: function(data)
{
... // whatever you want to do
var alertMessage = data.message;
if (data.correct_answer) {
alertMessage += ' ' + data.correct_answer;
}
alert(alertMessage); // show response
}
});
});
</script>

html表单将转到actionurl。如果您希望在没有reload的情况下对页面进行某些更改或函数,则需要使用js

在web应用程序中,通常需要显示通知消息(也称为"flash消息"(之后发送给用户处理表单或某些其他类型的用户输入。

为此,Django提供了对基于cookie和会话的完全支持消息传递,适用于匿名用户和经过身份验证的用户。消息框架允许您将消息临时存储在一个请求中检索它们以在随后的请求中显示(通常是下一个一(。每条消息都用特定级别进行标记,以确定其优先级(例如,信息、警告或错误(。

有关实现消息的信息,请参阅:https://docs.djangoproject.com/en/1.11/ref/contrib/messages/

最新更新