我有一个小问题。例如,我有以下视图:
def post_create(request):
form = PostForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
# message success
messages.success(request, "Successfully Created")
return HttpResponseRedirect(instance.get_absolute_url())
else:
messages.error(request, "Not Successfully Created")
context = {
"form": form,
}
return render(request, "post_form.html", context)
主要问题:重定向后,我同时收到了两条消息(如果同时出现)。为什么?
解决方案是:
... ...
return HttpResponseRedirect(instance.get_absolute_url())
elif form.errors:
messages.error(request, "Not Successfully Created")
context = {
"form": form,
}
return render(request, "post_form.html", context)
但是为什么我在成功验证后重定向(第一种变体)时会看到两条消息?
base.html:
{% load staticfiles %}
<!--DOCTYPE html -->
<html>
<head>
<title></title>
<link rel='stylesheet' href='{% static "css/base.css" %}' />
<style>
{% block style %}{% endblock style %}
</style>
</head>
<body>
{% include "messages_display.html" %}
<div class='container'>
{% block content %}{% endblock content %}
</div>
</body>
</html>
messages_display.html:
{% if messages %}
<div class='messages'>
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{% if "html_safe" in message.tags %}{{ message|safe }}{% else %}{{ message }}{% endif %}</li>
{% endfor %}
</ul>
</div>
{% endif %}
post_form.html:
{% extends "base.html" %}
{% block content %}
<div class='col-sm-6 col-sm-offset-3'>
<h1>Form</h1>
<form method='POST' action=''>{% csrf_token %}
{{ form.as_p }}
<input type='submit' class='btn btn-default' value='Create Post' />
</form>
</div>
{% endblock content %}