[Django]如何在不刷新页面的情况下,在提交表单后显示一条消息(正确或错误)?

[Django]How to display a message(correct or incorrect) after submitting the form, without refreshing the page?

我制作了一个测验页面,使用 "checkans" 函数检查用户的答案是否正确。如果答案正确,我想 return 发送 "Correct" 消息;如果答案不正确,我想发送 "Incorrect" 消息。现在我可以 "kind of" 做,但不是我想要的。现在它 return 是重定向到一个全新页面后的消息,问题框和其他所有内容都完全消失,只有消息。

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

这是我的观点:

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="ans">Answer:</label>
                <input type="text" name="ans"/>
                <input type="submit" value="Submit"/>
            </form>
        <input type="submit" value="Skip"/>

        </div>
</div>
{% else %}
{% if message %}
        <div class="message">
            {{ message }}
        </div>
        <div class="ans">
            {{ 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 表单将转到 action url。如果你想在没有 reload 的页面中进行一些更改或功能,你需要使用 js.

Quite commonly in web applications, you need to display a one-time notification message (also known as “flash message”) to the user after processing a form or some other types of user input.

For this, Django provides full support for cookie- and session-based messaging, for both anonymous and authenticated users. The messages framework allows you to temporarily store messages in one request and retrieve them for display in a subsequent request (usually the next one). Every message is tagged with a specific level that determines its priority (e.g., info, warning, or error).

实现消息参考:https://docs.djangoproject.com/en/1.11/ref/contrib/messages/