stopping django messages from showing error message and success message at once

試著忘記壹切 提交于 2020-01-25 01:50:15

问题


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.

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.

VIEW CODE:

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)

TEMPLATE of saved post:

<!-- 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>

回答1:


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.

THE FIX:
change

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

to

elif form.errors:

Now the flash messages should display under the correct conditions



来源:https://stackoverflow.com/questions/36650104/stopping-django-messages-from-showing-error-message-and-success-message-at-once

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!