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

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

Context is not displaying in the template when using ListView

问题

  1. 我无法理解为什么在HTML模板中什么都没有显示出来。
  2. class TrainersListView(ListView):
  3. model = Profile
  4. template_name = 'trainers.html'
  5. def get_context_data(self, **kwargs):
  6. context = super().get_context_data(**kwargs)
  7. _list = Profile.objects.filter(city__slug=self.kwargs['slug']).order_by('id')
  8. context['trainers'] = _list
  9. print(len(context['trainers']) --> 返回 5
  10. **HTML**
  11. {% for trainer in trainers %}
  12. {{ trainer.id }}
  13. {% endfor %}
  14. 即使我删除了所有实例
  15. _list = Profile.objects.all()
  16. 仍然是空白结果
  17. 我做得对吗?
英文:

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

  1. class TrainersListView(ListView):
  2. model = Profile
  3. template_name = 'trainers.html'
  4. def get_context_data(self, **kwargs):
  5. context = super().get_context_data(**kwargs)
  6. _list = Profile.objects.filter(city__slug=self.kwargs['slug']).order_by('id')
  7. context['trainers'] = _list
  8. print(len(context['trainers']) --> return 5

html

  1. {% for trainer in trainers %}
  2. {{ trainer.id }}
  3. {% endfor %}

Even if I take out all the instances

  1. _list = Profile.objects.all()

still a blank result
Am I doing everything right?

答案1

得分: 2

  1. def get_context_data(self, **kwargs):
  2. context = super().get_context_data(**kwargs)
  3. _list = Profile.objects.filter(city__slug=self.kwargs['slug']).order_by('id')
  4. context['trainers'] = _list
  5. print(len(context['trainers'])) # return 5
  6. return context
英文:

You forgot

  1. return context

  1. def get_context_data(self, **kwargs):
  2. context = super().get_context_data(**kwargs)
  3. _list = Profile.objects.filter(city__slug=self.kwargs['slug']).order_by('id')
  4. context['trainers'] = _list
  5. print(len(context['trainers']) --> return 5
  6. 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:

确定