我需要知道如何使评论所属的实际帖子名称在我的模板中可用,以便稍后在其上显示:
views.py
def comment_edit(request, pk):
comment = get_object_or_404(Comment, pk=pk)
if request.user == comment.author:
if request.method == "POST":
form = CommentForm(request.POST, instance=comment)
if form.is_valid():
comment = form.save(commit=False)
comment.author = request.user
comment.published_date = timezone.now()
comment.save()
return redirect('post_detail', pk=comment.post.pk)
else:
form = CommentForm(instance=comment)
return render(request, 'app/Post/post_comment_edit.html', {'form': form})
else:
return redirect('post_detail', pk=comment.post.pk)
template.html:
<a href="{% url 'post_list_by_category' pk=post.category.pk %}">{{ post.category.title }} </a>
<a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }} </a>
models.py
class Comment(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
content = models.TextField(max_length=500)
published_date = models.DateField(auto_now_add=True, null=True)
预先感谢
答案 0 :(得分:0)
将评论实例传递到您的模板
return render(request, 'app/Post/post_comment_edit.html', {'form': form, 'comment': comment})
和在模板中
<a href="{% url 'post_list_by_category' pk=comment.post.category.pk %}">{{ comment.post.category.title }} </a>
<a href="{% url 'post_detail' pk=comment.post.pk %}">{{ comment.post.title }} </a>