[使用ListView时上下文未显示在模板中

问题描述 投票:0回答:1

我不明白为什么html模板中什么都没有。

class TrainersListView(ListView):
    model = Profile
    template_name = 'trainers.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        _list = Profile.objects.filter(city__slug=self.kwargs['slug']).order_by('id')
        context['trainers'] = _list
        print(len(context['trainers']) --> return 5 

html

{% for trainer in trainers %}

{{ trainer.id }}
{% endfor %}

即使我删除了所有实例

_list = Profile.objects.all()

仍然是空白结果我做对了吗?

python django django-class-based-views
1个回答
2
投票

您忘记了

return context

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    _list = Profile.objects.filter(city__slug=self.kwargs['slug']).order_by('id')
    context['trainers'] = _list
    print(len(context['trainers']) --> return 5

    return context

文档:Generic display views

© www.soinside.com 2019 - 2024. All rights reserved.