“当使用ListView时,模板中未显示上下文”

huangapple go评论86阅读模式
英文:

Context is not displaying in the template when using ListView

问题

我无法理解为什么在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']) --> 返回 5 

**HTML**

{% for trainer in trainers %}
    
{{ trainer.id }}
{% endfor %}

即使我删除了所有实例

_list = Profile.objects.all()

仍然是空白结果
我做得对吗?
英文:

I can't understand why nothing comes out in the html template.

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 %}

Even if I take out all the instances

_list = Profile.objects.all()

still a blank result
Am I doing everything right?

答案1

得分: 2

    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
英文:

You forgot

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

Doc: Generic display views

huangapple
  • 本文由 发表于 2020年1月3日 21:52:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/59579763.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定