[英]How to pass in the context of a Class Based View to the Template in Django?
我在 Django 中有一个脚本,所有用户都可以在其中查看另一个用户的个人资料。 我可以使用 get_queryset 方法获得有关 CBV ListView 问题的答案。 我现在可以访问另一个用户的个人资料,但我无法将其传递到我的主页模板中。
视图.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
网址.py
path('profile/<int:user_id>/', OtherUserProfileView.as_view(), name='profile'),
在 View.py 中,我使用了 ListView 和 get_queryset 方法。 我传入了 user_id,这样我就可以访问另一个用户的所有对象。
首页.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 at / Reverse for 'profile' with keyword arguments '{'user_id': ''}' 未找到。 尝试了 1 种模式:['profile/(?P<user_id>[0-9]+)/$']
将get_context_data
方法添加到视图
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.