停止django消息一次显示错误消息和成功消息 [英] stopping django messages from showing error message and success message at once

查看:51
本文介绍了停止django消息一次显示错误消息和成功消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标:我正在构建一个简单的博客应用程序.在我的帖子视图中,有一个名为post_create的视图,假设没有帖子请求时,该视图首先显示表单.在提交表单时,将邮寄请求发送到同一视图,然后有条件地检查表单是否有效.如果表单数据有效,则重定向将发送成功消息并发送到帖子.如果重定向无效,则请求将被发送回origianl post_create视图,并显示一条错误消息.

GOAL: I am building a simple blog application. Within my post views there is one view called post_create that is suppose to first reveal the form if there is no post request. On form submit the post request is sent to that same view and a conditional then checks if the form is valid or not. If the form data is valid the redirect gets sent to the post with a success message. If the redirect is not valid the request gets sent back to the origianl post_create view with an error message.

问题:当我第一次通过提交缺少的数据来测试表单时,我被定向回到原始表单页面和错误消息,这很好.但是,然后我用所有正确的数据填写了表单,然后将我重定向到了Post,同时看到了错误消息和成功消息.我应该只看到成功消息.

ISSUE: When I first test out the form by submitting missing data I get directed back to the original form page and error message, which is good. But then I fill the form out with all the correct data and I get redirected to the Post I see the error message and the success message simultaniously. I should just see the success message.

查看代码:

def post_create(request):
form = PostForm(request.POST or None)
if form.is_valid() and request.method == 'POST':
    instance = form.save(commit=False)
    instance.save()
    # message success
    ## TODO GET MESSAGES TO NOT DISPLAY SUCCESS AND FAILURE
    messages.add_message(request,messages.SUCCESS, "Logged in Successfully")
    return HttpResponseRedirect(instance.get_absolute_url())
elif(request.method == 'POST'):
    messages.error(request, "Not Successfully Created")


context = {
    "form":form,
}
return render(request,"post_form.html",context)

已保存帖子的模板:

<!-- DOCTYPE html -->

<html>
    <body>
        {% if messages %}
        <ul class="messages">

            {% for message in messages %}
            <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
            {% endfor %}
        </ul>
    {% endif %}

        <h1>{{ post.title}}</h1>
        <div>
            {{post.content}}</br>
            {{post.timestamp}}</br>
            {{post.id}}</br>
        </div>
    </body>
</html>

推荐答案

默认情况下,该表单无效.因此,您的"elif"条件在这里不起作用,每次提交表单时都会显示错误消息.但是,如果成功提交了表单,则不会有任何错误,因此检查 form.errors 会真正起作用.

The form is invalid by default. So your 'elif' condition won't work here, the error message will show up every time the form is submitted. But if the form is successfully submitted, there wouldn't be any errors, hence checking form.errors will actually work.

修复:
改变

elif(request.method == 'POST'):

elif form.errors:

现在Flash消息应该在正确的条件下显示

Now the flash messages should display under the correct conditions

这篇关于停止django消息一次显示错误消息和成功消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆