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>