django - 如果之前已经编辑过评论,如何使其在评论旁边显示“已编辑”的永久消息?
问题描述
如果之前已经编辑过评论,如何使其在评论旁边显示“已编辑”的永久消息?这样每个人都可以看到之前已经编辑过评论。(如果我也可以保留原始预编辑消息的副本会很好,但是如果那太难了,我只是希望在评论旁边显示一条“已编辑”的永久消息。
模型.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)
视图.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 描述了您可以拥有的最佳解决方案,将其添加到您的Comment
模型中:
edited = models.BooleanField(default=False)
然后在您的视图中,只要在调用之前对评论进行编辑,comment.save()
请执行以下操作:
comment.edited = True
在您列出评论的html中执行以下操作:
{% for comment in comments %}
<p>{{ comment.name }} : {{ comment.body }}</p>
{% if comment.edited %}
<p>edited</p>
{% endif %}
{% endfor %}
推荐阅读
- excel - 粘贴到 Excel VBA 会导致无限循环
- linux - 如何将 bash stderr 重定向到终端,但也将带有 stdout 的 stderr 重定向到日志文件?
- makefile - 新目标如何使用附加参数调用先前的目标?
- python - 如何导入自制模块?
- angular - 导航后实现逻辑
- angular - 使用 .pipe() 在 Angular 中检索响应标头
- ios - 在 coredata 中过滤 Vs NSPredicate
- css - 在伪元素未出现在路径元素上之前
- swiftui - 在 SwiftUI 中使用 Timer 触发 NavigationView 更改的正确方法
- asp.net - 我想将我的 rdlc 报告转换为土耳其语