Python 3 - Django 1.9一个创建请求导致多次创建尝试?

时间:2018-01-28 07:58:03

标签: python django python-3.x

我正在添加一条成功或不成功的消息,以便在我开始获取该帖子创建成功并且同时失败时创建帖子时学习制作博客项目:

Current Result

使用if / else语句定义消息的内容,我唯一能想到的就是当我在我的帖子创建表单上单击提交时,它被多次提交导致初始成功尝试然后两次失败尝试但我没有看到在views.py,post_form.html或post_detail.html文件中发生这种情况的原因。有没有人知道如何解决这个问题?

views.py

from django.contrib import messages
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404

from .forms import PostForm
from .models import Post

def post_create(request):
    form = PostForm(request.POST or None)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        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)

post_form.html

<!--DOCTYPE html -->

<html>
<head>
    <title></title>
</head>
<body>
    <h1>Form</h1>

<form method="POST", action="">{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="Create Post"/>
</body>
</html>

post_detail.html

<!--DOCTYPE html -->

<html>
<head>
    <title></title>
</head>

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

<body>
    <h1>{{ title }}</h1>

{{ instance.title }}<br/>
{{ instance.content }}<br/>
{{ instance.timestamp }}<br/>
{{ instance.updated }}<br/>
{{ instance.id }}<br/>
<br/>

</body>
</html>

0 个答案:

没有答案