通用视图概述
很多情况下使用视图来显示一个列表或者一个对象的详细信息。正是由于类似的工作比较常见,因此Django提供了一些通用类视图。
下面仍然以Blog应用程序为例展示如何使用通用类视图。
编写视图。
from django.views.generic import ListView
from .models import Blog
class BlogListView(ListView):
model = Blog
修改URL。
path(r'index/', views.BlogListView.as_view(), name='index'),
创建模板。
以上就是全部的Python代码,下面添加模板。对于ListView,Django会自动查找名为“模型_list.html”模板,本例中默认模板名为“blog_list.html”
。在templates文件夹下创建“blog/blog_list.html”
:
{% extends "base.html" %}
{% load static %}
{% block content %}
{% for blog in object_list %}
<h2 class="blog_head">{{ blog.id }} - {{ blog.name }} </h2>
<p class="blog_body">
{{ blog.tagline }}
</p>
{% endfor %}
{% endblock %}
注意,由于ListView是通用视图,所以它传递给模板的上下文对象是object_list而不是具体的模型名。
浏览器访问效果如图所示。
修改通用视图属性
前面在使用ListView时采用的是默认属性,如模板名和上下文对象,默认值虽然方便但是却难以理解,下面我们就试着修改默认值:
class BlogListView(ListView):
model = Blog
template_name = 'blog_list.html'
context_object_name = 'blogs'
将原有模板名重命名为“blog_list.html”
,上下文对象修改为“blogs”
。在浏览器中重新访问效果一样。
添加额外的上下文对象
有时我们在模板中不只需要默认的模型数据列表,可能还需要额外的一些信息,或者我们需要对数据列表进行一定的修改,此时可以通过重写get_context_data()方法达到这样的目的。
下面修改代码使博客列表中只显示最近发布的三篇文章,并显示全部作者:
修改模板:
class BlogListView(ListView):
model = Blog
template_name = 'blog_list.html'
context_object_name = 'blogs'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['entries'] = Entry.objects.all().order_by('pub_data'[0:3])
context['author_list'] = Author.objects.all()
return context
修改视图:
{% extends "base.html" %}
{% load static %}
{% block content %}
<ul>
{% for author in author_list %}
<li>
{{ author.name }}
</li>
{% endfor %}
</ul>
{% for entry in entries %}
<h2 class="blog_head">{{ entry.blog.id }} - {{ entry.blog.name }}</h2>
<p class="blog_body">
{{ entry.blog.tagline }}
</p>
{% endfor %}
{% endblock %}
浏览器访问效果如图所示。
queryset属性
前面我们使用“model = Blog”
在通用视图中指定模型,其实这句代码是queryset的简写形式,标准写法是:
queryset = Publisher.objects.all()
通过使用queryset可以对数据进行一定的修改,下面重新编写BlogListView:
此时网页将只显示前三篇博客文章。
通用视图参数
通用视图也可以传递参数,下面的URL允许接收Author作为过滤条件。
path(r'index/<author>/', views.BlogListView.as_view()),
修改BlogListView视图:
class BlogListView(ListView):
model = Entry
template_name = 'blog/blog_list.html'
context_object_name = 'entries'
def get_queryset(self):
self.author = get_object_or_404(Author, name=self.kwargs['Author'])
return Entry.objects.filter(author=self.author)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['author_list'] = Author.objects.all()
return context
修改模板:
{% extends "base.html" %}
{% load static %}
{% block content %}
<ul>
{% for author in author_list %}
<li>
{{ author.name }}
</li>
{% endfor %}
</ul>
{% for entry in entries %}
<h2 class="blog_head">{{ entry.blog.id }} - {{ entry.blog.name }}</h2>
<p class="blog_body">
{{ entry.blog.tagline }}
</p>
{% endfor %}
{% endblock %}
浏览器显示效果如图所示。
通用视图与模型
从上面示例代码不难发现,某些视图指定了model属性,而某些视图并没有给出model属性,但是所有这些视图都能够很好地工作,这是由于通用视图可以从以下三个方面确定模型:
- 视图的model属性指定模型。
- 视图的get_object()方法返回模型。
- 视图的queryset所使用的模型。
酷客教程相关文章:
评论前必须登录!
注册