如何在new_comment页面上显示帖子名称

时间:2019-05-12 19:24:43

标签: python django

我想知道如何在我的comment_new页面上显示帖子的名称:

views.py

def comment_new(request, pk):
    if request.method == "POST":
        form = CommentForm(request.POST)
        post = get_object_or_404(Post, pk=pk)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.author = request.user
            comment.published_date = timezone.now()
            comment.post = post
            comment.save()
            messages.success(request, 'You have successfully provided a comment for this Post.')
            return redirect('post_detail', pk=comment.post.pk)
        else:
            form = CommentForm(request.POST)
            return render(request, 'app/comment_new.html', {'form': form})
    else:
        form = CommentForm()
        return render(request, 'app/comment_new.html', {'form': form})

models.py

class Post(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(verbose_name="Post Title", max_length=40)
    content = models.TextField(verbose_name="Post Content", max_length=5000)
    tag = models.CharField(verbose_name="Tags/Meta - (sep. by comma)", max_length=50, blank=True)
    category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True)

template.html

<a>{{ post.title }}</a>

给出了属性标题。我不知道为什么它不起作用。

预先感谢

1 个答案:

答案 0 :(得分:1)

我假定您要在用户要添加新评论时显示帖子标题。我的意思是,当请求是GET时(显示新的消息表单)。

def comment_new(request, pk):

    # This line is better here since you'll be working with
    # the post instance no matter the request method is POST or GET.
    post = get_object_or_404(Post, pk=pk)

    if request.method == "POST":
        # ...
    else:
        form = CommentForm()
        # And here pass post as part of the context to your template.
        return render(request, 'app/comment_new.html', {'form': form, 'post': post})