[英]Getting filtered objects from url by passing correct attributes
I have a Django app with posts and comments with comments linked to the posts with foreign keys. 我有一个Django应用,其中包含帖子和带有外键链接到帖子的评论。 I am unable to fetch the comments for a particular post. 我无法获取特定帖子的评论。
I checked my DB to make sure the foreign key is getting added correctly and it is. 我检查了数据库,以确保正确添加了外键。 I tried changing the attribute name multiple times with no effect. 我尝试多次更改属性名称没有任何效果。
My html code in the post detail template for get all comments button is as below: 我在获取详细信息按钮的详细信息模板中的html代码如下:
<a class="btn btn-outline-info mb-4" href="{url 'user-comments' object.id}">View Answers</a>
My views.py looks like this: 我的views.py看起来像这样:
class PostCommentListView(ListView):
model = Comment
template_name = 'blog/comment.html'
context_object_name = 'comments'
ordering = ['-comment_date']
paginate_by = 7
def get_queryset(self):
post = get_object_or_404(Comment, post_id=self.kwargs.get('post_id'))
return Comment.objects.filter(post=post).order_by('-comment_date')
and the url 'user-comments' is as follows: 网址“用户评论”如下:
path('post/<int:post_id>', PostCommentListView.as_view(), name='user-comments')
I am getting a page not found message. 我收到找不到页面的消息。
Request URL: http://127.0.0.1:8000/post/15/%7Burl%20'user-comments'%20object.id%7D
The current path, post/15/{url 'user-comments' object.id}, didn't match any of these.
You have a syntax error in your html page. 您的html页面中存在语法错误。
<a class="btn btn-outline-info mb-4" href="{url 'user-comments' object.id}">View Answers</a>
This should be written as: 这应该写为:
<a class="btn btn-outline-info mb-4" href="{% url 'user-comments' object.id %}">View Answers</a>
Please make sure you have properly maintained the syntax in your codes. 请确保您已正确维护代码中的语法。
在Django模板中,应在{% %}
标签内调用url
。
<a href="{% url 'user-comments' object.id %}">View Answers</a>
You url path should also have post id, which will show comments of one particular post. 您的url路径还应该具有帖子ID,该ID将显示一篇特定帖子的评论。
class PostCommentListView(ListView):
model = Comment
template_name = 'blog/comment.html'
context_object_name = 'comments'
ordering = ['-comment_date']
paginate_by = 7
def get_queryset(self):
qs = super(PostCommentListView, self).get_queryset()
post = get_object_or_404(Post, id=self.kwargs['post_id'])
qs = qs.filter(post=post)
return qs
## Then, in urls.py you should have your url path like this
path('posts/<int:post_id>/comments', views.PostCommentListView.as_view(),
name='user-comments'),
In Django templates also, url
should be called inside {% %}
tags. 同样在Django模板中,应在{% %}
标签内调用url
。
<a class="btn btn-outline-info mb-4" href="{% url 'user-comments' object.id %}">View Answers</a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.