ListView
本课属于 Coddy Django 学习旅程的“基于类的视图”单元。第 4 课,共 18 课。
看板需要一个列出所有工作的页面。列出表中所有行是很常见的需求,因此 Django 编写了这个视图:ListView。给它一个模型,它就会查询这些行,并用它们渲染模板。下面是应用 recipes 中菜谱网站的列表视图:
from django.views.generic import ListView
class RecipeListView(ListView):
model = Recipe
context_object_name = "recipes" # {% for recipe in recipes %}
ordering = ["minutes"] # 耗时最短的排在前面如果没有设置 template_name,它会渲染 recipes/recipe_list.html:应用标签、小写的模型名称,然后是 _list.html。模板始终会通过 object_list 获取这些行。它还会通过 recipe_list 获取这些行;如果你设置了 context_object_name,则会改用你设置的名称。
ordering 接受 order_by() 接受的值,因此 ["-minutes"] 会把耗时最长的菜谱放在最前面。如果不设置它,这些行会按照数据库中的顺序排列。
挑战
简单添加职位页面,使用现成的模板 jobs/job_list.html,该模板会遍历 jobs。
- 在
jobs/views.py中添加JobListView,它是一个用于Job的ListView。将列表命名为jobs,按posted日期从新到旧排序,并保留默认模板。 - 在
jobs/urls.py中添加名为list的路由"jobs/"。
打开 /jobs/:Python Developer 排在第一位,Technical Writer 排在最后一位。
亲手试试
from django.views.generic import TemplateView
from .models import Job
class HomeView(TemplateView):
template_name = "jobs/home.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["count"] = Job.objects.count()
context["latest"] = Job.objects.order_by("-posted").first()
return context
class AboutView(TemplateView):
template_name = "jobs/about.html"
基于类的视图中的所有课
自己练习: Django 在线编辑器