Django:刷新内容时再次发布[重复内容]

2024-04-19 20:58:05 发布

您现在位置:Python中文网/ 问答频道 /正文

发布的内容和上次发布的内容相同,但我还是从上次发布的内容更新了。。在

在模型.py在

class chat_content(models.Model):
    content = models.CharField(max_length=500)

    def __str__(self):
        return self.content

在视图.py在

^{pr2}$

在表单.py在

class cont(forms.ModelForm):
    class Meta:
        model = chat_content
        fields = ('content',)

.html格式

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
Welcome to the public discussion
{% for c in cnt %}
<div>
    {{ c }}
</div>
{% endfor %}
<form action="." method="post" enctype="multipart/form-data" >
    {% csrf_token %}
    {{ form }}

</form>
</body>
</html>

刷新时如何避免重复??在

例如

最后一条评论是:“欢迎大家”

刷新页面时,内容更新为重复并显示为:“欢迎所有人”“欢迎所有人”

在哪里我可以纠正这些重复?? 在这段代码中有没有使用ajax的简单方法??在

提前谢谢。。在


Tags: py模型selfdivform内容titlemodels
1条回答
网友
1楼 · 发布于 2024-04-19 20:58:05

您不需要显示HTML页面,而是需要在发布后重定向到此页面:

from django.shortcuts import redirect

form = cont(data=request.POST)
if form.is_valid():
    form.save()
    return redirect(home)

在这种情况下,用户将刷新GET页面,这样内容就不会重复。在

相关问题 更多 >