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

2024-06-02 08:28:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我制作了一个测验页面,它使用“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="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 %}

Tags: 答案divid消息messagegetrequestcontext
2条回答

您需要的是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

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/

相关问题 更多 >