【发布时间】:2021-02-08 08:12:41
【问题描述】:
我在 Django 中有一个脚本,所有用户都可以在其中查看另一个用户的个人资料。我可以使用 get_queryset 方法获得有关 CBV ListView 问题的答案。我现在可以访问其他用户的个人资料,但无法将其传递到我的主页模板中。
View.py
class OtherUserProfileView(LoginRequiredMixin, ListView):
model = Post
template_name = "core/otheruser.html"
def get_queryset(self):
queryset = super().get_queryset()
queryset = queryset.filter(user_id=self.kwargs['user_id'])
return queryset
Urls.py
path('profile/<int:user_id>/', OtherUserProfileView.as_view(), name='profile'),
在 View.py 中,我使用了 ListView 和 get_queryset 方法。我传入了 user_id,所以我可以访问另一个用户的所有对象。
Home.html
{% extends "core/base.html" %}
{% block content%}
{% for item in object_list%}
<div class="container">
<div class="card text-light bg-secondary mb-3 mx-auto" style="max-width: 60rem;">
<div class="card-header text-light">{{item.title}}</div>
<div class="card-body">
<p class="card-text text-light">{{item.content}}</p>
<h6 class="card-title text-light"><a class="text-light" href="{% url 'core:detail' item.pk %}">Full Page</a></h6>
<p class="card-text text-light"><a class="text-light " href="{% url 'core:profile' user_id=view.kwargs.user_id %}">{{item.user}}</a><small class="text-light"> {{item.created}} </small></p>
</div>
</div>
</div>
{% endfor%}
{% endblock %}
但是,当我尝试传入脚本 <a class="text-light " href="{% url 'core:profile' user_id=view.kwargs.user_id %}">{{item.user}}</a> 时,我收到一条错误消息
NoReverseMatch 在 /
使用关键字参数 '{'user_id': ''}' 反转'profile'。尝试了 1 种模式:['profile/(?P
【问题讨论】:
-
试试
item.user_id:{% url 'core:profile' user_id=item.user_id %} -
酷!它确实有效。谢谢!!!!