Django 模板未从 URL 接收值

Django template not receiving value from URL

Django 专家和爱好者们大家好!

我有以下情况(源码在本post末尾):

我有一个模板供 DetailView 用于 post 模型(即显示 post 的特定实例的详细信息)。在这个模板中,我在模板中有 context_object_name post - 该对象有一个 ID。在这个 DetailView 中,有一个 URL link 到另一个 CreateView 模板。该创建视图用于 comment 模型。 postcomment 之间存在外键关系 - 一个 post 可以有 0 - 更多评论。

当我单击 post 的 DetailView 时,我有一个 link 用于 CreateView 以供评论。当用户为 post 写评论并点击 保存按钮 时,我需要在 CreateView 模板中的模板中提供 post.id (我想将其作为评论表单中的隐藏字段发送,以便 comment 模型在 save() 方法中具有 post.id 可用 - 这将满足保存时对外键的需求 评论)。

现在谈谈我的问题:

我想将 post.id 从 DetailView 模板发送到 CreateView 模板(这样我就可以将其用作隐藏表单)。问题是,CreateView 的模板未收到 post.id 以供评论。满足我需求的源代码如下:

DetailView 模板(post),即 url linking 到 CreateView(comment ):

<a  class="btn btn-danger" href="{% url 'commentpost' post_id=post.id %}">Reagovat</a>

应用程序级别的一行 urls.py 照顾 commentpost URL:

path('commentpost/<int:post_id>/',CommentPostView.as_view(),name='commentpost')

我在想 commentpost URL 的模板应该有 {{ post_id }} 可用的值...但是,commentpost 模板是空的 - > 评论模板中的一行post: <tr><td>ID:{{ post_id }}</td></tr>.

创建评论视图:

class CommentPostView(CreateView):
    model = Comment
    context_object_name = 'comment'
    form_class = NewCommentForm
    template_name = 'new_comment.html'

评论模型:

class Comment(models.Model):
    post = models.ForeignKey(Post,on_delete=models.CASCADE)
    author = models.CharField(max_length = 100, choices = DEPARTMENTS)
    date_sent = models.DateTimeField()
    text = models.TextField(max_length = 255)

基本上流程应该是这样的: 1) DetailView 模板发送 post_id -> 2) urls.py 处理 post_id 值 - 调用正确的视图 3) 查看渲染模板和接收 post_id 值的模板。

我 100% 确定步骤 1) 中的 post_id 值不为空。步骤 1) 的 URL 即 DetailView 如下所示:http://192.168.56.101:8080/detailpost/1360

你们知道我错过了什么吗?

非常感谢您的任何建议,保重。

get_context_data 方法将使 post_id 在模板中可用:

class CommentPostView(CreateView):
    model = Comment
    context_object_name = 'comment'
    form_class = NewCommentForm
    template_name = 'new_comment.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['post_id'] = self.kwargs.get('post_id', None)
        return context

@Radico 的回答很好。另一种方法是在视图中获取对象(如果您需要 id 旁边的其他字段)。在模板中,您可以通过 object.id

访问它
def get_object(self, queryset=None):
    return get_object_or_404(Post, pk=self.kwargs['post_id'])