django - 如何使得如果以前编辑过评论,则评论旁边会显示 "edited"永久消息?

标签 django django-models django-views django-forms django-templates

如何使得如果评论之前被编辑过,则评论旁边会显示“已编辑”永久消息?这样大家就能看到该评论之前已经被编辑过。 (如果我也能保留原始预编辑消息的副本,那就太好了,但如果这太难了,我只是希望在评论旁边显示一条“已编辑”的永久消息。

模型.py

class Comment(models.Model):
   post = models.ForeignKey(BlogPost, related_name='comments', on_delete=models.CASCADE)
   name = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='name', on_delete=models.CASCADE)
   body = models.TextField()

class BlogPost(models.Model):
 title                  = models.CharField(max_length=50, null=False, blank=False, unique=True)
 author                     = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
 slug                   = models.SlugField(blank=True, unique=True)

View .py

def edit_own_comment(request, post_id):
    context = {}
    comment = get_object_or_404(Comment, id=post_id)
    if request.method == 'POST':
        form = UpdateCommentForm(request.POST or None, instance=comment)
        if form.is_valid():
            obj.save()
            messages.success(request, 'Your comment has been edited', extra_tags='editedcomment')
            return redirect(reverse("HomeFeed:detail", kwargs={'slug': comment.post.slug }))

    form = UpdateCommentForm(
            initial = {
                    "body": comment.body,
            }
        )

    context['form'] = form
    return render(request, 'HomeFeed/edit_comment.html', context)


class DetailBlogPostView(BlogPostMixin,DetailView):
    template_name = 'HomeFeed/detail_blog.html'
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        blog_post=self.get_object()
        blog_post.save()

表单.py

class UpdateCommentForm(forms.ModelForm):
 class Meta:
  model = Comment
  fields = ['body']

 def save(self, commit=True):
  comment = self.instance
  comment.body = self.cleaned_data['body']

  if commit:
   comment.save()
  return comment

详细信息.html

  {% for comment in blog_post.comments.all %}
    {{ comment.name}}
  {{ comment.body }}
  {% endfor %}

最佳答案

好吧,Ankush 描述了您可以拥有的最佳解决方案,请将其添加到您的评论 模型:

edited = models.BooleanField(default=False)

然后,在调用 comment.save() 之前编辑评论时,在您的 View 中执行以下操作:

comment.edited = True

在您列出评论的 html 中,执行以下操作:

{% for comment in comments %}
    <p>{{ comment.name }} : {{ comment.body }}</p>
    {% if comment.edited %}
        <p>edited</p>
    {% endif %}
{% endfor %}

关于django - 如何使得如果以前编辑过评论,则评论旁边会显示 "edited"永久消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65883818/

相关文章:

Django/表单 : How can i validate initial data against received data (if match)?

python - 如何从 Django 注册表单中的密码字段获取纯密码

python - 在 get_queryset 中返回一个 Http 响应

python - 尽管迁移已成功完成,但 Admin 或 Api 没有发生任何更改

python - 如何在 Django 用户名中允许空格?

python - Django ManyToManyField 中的 'through' 参数是否包含所有字段?

Python模型继承和模型声明的顺序

django - 不存在匹配查询?

django - 如何创建涉及使用 @property 方法进行计算的 POST 方法

jquery 自动完成未定义函数