stopping django messages from showing error messag

2019-07-29 07:16发布

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>

标签: django forms
1条回答
三岁会撩人
2楼-- · 2019-07-29 08:13

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

查看更多
登录 后发表回答