安迪_963

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

主要功能是渲染模板,看官例:

 

from django.views.generic.base import TemplateView
from articles.models import Article
class HomePageView(TemplateView):
template_name = "home.html"
def get_context_data(self, **kwargs):
context = super(HomePageView, self).get_context_data(**kwargs)
context['latest_articles'] = Article.objects.all()[:5]
return context
Views.py

 

 

from django.conf.urls import url
from myapp.views import HomePageView
urlpatterns = [
url(r'^$', HomePageView.as_view(), name='home'),
]
urls.py

 

 

它继承了这三个基类:

•django.views.generic.base.TemplateResponseMixin
•django.views.generic.base.ContextMixin
•django.views.generic.base.View

它的处理流程是:

1.dispatch()
2.http_method_not_allowed()
3.get_context_data()

前面两部与之前的django.views.generic.base.View是一样的。

看看get_context_data(**kwargs)

它的作用是返回一个代表模板文本(环境)的字典,关键字参数将用来组成返回的文本的一部分。

例如:

 

def get_context_data(self, **kwargs):
context = super(RandomNumberView, self).get_context_data(**kwargs)
context['number'] = random.randrange(1, 100)
return context

 

 

 

 这类视图文本包含一个指向视图实例的变量

注意:为避免暴露模对板作者造成潜在危害的模板方法,可以将alters_data 设置成True

它(TemplateView)的Context将由从url模式中捕获的关键字参数来填充

posted on 2016-09-08 07:40  Andy_963  阅读(1552)  评论(0编辑  收藏  举报