【问题标题】:[Django]How to display a message(correct or incorrect) after submitting the form, without refreshing the page?[Django]提交表单后如何在不刷新页面的情况下显示消息(正确或错误)?
【发布时间】:2024-01-16 19:27:01
【问题描述】:

我做了一个测验页面,它使用“检查”功能检查用户的答案是否正确。如果答案正确,我想返回“正确”消息,如果答案不正确,我想返回“不正确”消息。现在我可以“有点”去做,但不完全是我想要的。现在它在重定向到一个全新的页面后返回消息,问题框和其他所有内容都完全消失了,只有消息。

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

这是我的看法:

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 %}

【问题讨论】:

    标签: python html django message


    【解决方案1】:

    你需要的是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 网址。如果您希望页面中的某些更改或功能没有reload,则需要使用js

    【讨论】:

    • 首先,谢谢。我以前从未使用过 Ajax,所以我想我需要一些时间来弄清楚这一切。我想知道 Ajax 是否必要?还有其他方法吗?
    • 老实说,我不知道)。当某些事情需要DOM 更改时(例如添加到html 一些元素的添加、删除或更改),我使用js。所以,因为您将request 发送到后端,所以我认为ajax 是正确的解决方案。也许,您可以查看@vishal-singh 的答案以找到Django 方式的解决方案。但是,如果您使用的请求太多需要前端操作,我认为将ajax 添加到您的项目中将是一个很好的解决方案)
    • 经过一番研究,我认为 Ajax 也是更好的方法。但是在使用上面的代码后我不知道如何解决......在我插入您的代码后它仍然会转到另一个页面显示“消息”。我还需要改变什么?
    • @ProudHKer 我已经编辑了我的答案,将.submit 更改为.on('submit', ...)
    • 还是不行...e.preventDefault() 应该会停止提交表单并让页面保持不变,对吧?它会立即进入下一页:[checkans/id/?csrfmiddlewaretoken=................]。我猜AJAX根本不加载。但我不知道为什么。
    【解决方案2】:

    在web应用中很常见,需要一次性显示 之后向用户发送通知消息(也称为“闪信”) 处理表单或其他一些类型的用户输入。

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

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

    【讨论】:

      最近更新 更多