【发布时间】:2021-09-07 22:07:54
【问题描述】:
“topic_posts”的反面在其他地方也可以正常工作。但这在这里不起作用。 HTML 文件
<td class="align-middle">
{% with post=board.get_last_post %}
<small>
<a href="{% url 'topic_posts' board.id post.topic.id %}">
By {{ post.created_by.username }} at {{ post.created_at }}
id - {{ board.id }} {{ post.topic.id }}
</a>
</small>
{% endwith %}
</td>
网址设置
path('boards/<int:board_id>/topics/<int:topic_id>/', views.topic_posts, name='topic_posts'),
topic = get_object_or_404(Topic, board_id=board_id, id=topic_id)
return render(request, 'topic_posts.html', {'topic': topic})
当我将 board.id 和 post.topic.id 更改为整数值时,例如 1 和 24,网络将呈现。我评论了<a href="{% url 'topic_posts' board.id post.topic.id %}">并添加了{{ board.id }} {{ post.topic.id }},看看查询是否有错误,结果没有问题,它会在网页上呈现1、24。然后我试了<a href="{% url 'topic_posts' board.id 24 %}">,效果很好,但是<a href="{% url 'topic_posts' board.id post.topic.id %}">还是不行。
class Board(models.Model):
name = models.CharField(max_length=30, unique=True)
description = models.CharField(max_length=100)
def __str__(self):
return self.name
def get_posts_count(self):
return Post.objects.filter(topic__board=self).count()
def get_last_post(self):
return Post.objects.filter(topic__board=self).order_by('-created_at').first()
感谢阅读!
【问题讨论】:
-
模板代码是否在for循环中?似乎当
board.id=3然后post.topic.id是空的。这就是错误(3, '')告诉您的内容。你能分享get_last_post的代码吗?这很可能没有返回任何东西。 -
您好,感谢您的阅读。我已经编辑了帖子。当我评论
<a href="{% url 'topic_posts' board.id post.topic.id %}"></a>时,{{ post.topic.id }}会给我 24 分 -
您的模板代码是否已在 for 循环中显示?当
board.id是3时,我认为您不会为{{ post.topic.id }}获得24。您可以通过在返回前在get_last_post中打印print(Post.objects.filter(topic__board_id=3).order_by('-created_at').first())来检查这一点。这可能是空的。 -
这个
id - {{ board.id }} {{ post.topic.id }}给了我 id - 1 24,这与错误“(3,”)相矛盾,错误board.idgives 3 ? -
是的,它在 for 循环中
标签: django django-urls django-url-reverse