【问题标题】:How to pass in the context of a Class Based View to the Template in Django?如何将基于类的视图的上下文传递给 Django 中的模板?
【发布时间】: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 %}

但是,当我尝试传入脚本 &lt;a class="text-light " href="{% url 'core:profile' user_id=view.kwargs.user_id %}"&gt;{{item.user}}&lt;/a&gt; 时,我收到一条错误消息

NoReverseMatch 在 / 使用关键字参数 '{'user_id': ''}' 反转'profile'。尝试了 1 种模式:['profile/(?P[0-9]+)/$']

【问题讨论】:

  • 试试item.user_id: {% url 'core:profile' user_id=item.user_id %}
  • 酷!它确实有效。谢谢!!!!

标签: python django


【解决方案1】:

在视图中添加get_context_data方法

Learn more here

【讨论】:

    猜你喜欢
    • 2020-12-23
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2014-09-11
    相关资源
    最近更新 更多