java view template_TemplateView , ListView ,DetailView三种常用类视图用法

TemplateView

个人理解:listview,detailview,templateview。前两个特别像,变量函数基本一样,templateview也差不多,只不过没有get_queryset()。

model=Atticle#指定了数据表。他的功能相当于取出了Article中的所有数据

template_name="blog/index.html"#指定页面

context_object_name="artcle_list"#listview默认使用object_list作为上下文变量。可使用context_object_name重命名。

get_context_data(self,**kwargs)#这个方法用来添加额外的内容到上下文变量中。

Example views.py:

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

Example urls.py:

from myapp.views import HomePageView

urlpatterns = [

'''

classmethod as_view(**initkwargs)¶

返回一个可调用的视图,它接受一个请求并返回一个响应:

response = MyView.as_view()(request)

'''

url(r'^$', HomePageView.as_view(), name='home'),

]

Example home.html:

{% for article in latest_articles%}

{{article.name}}

{% endfor %}

ListView、DetailView

个人理解:listview ,detailview的区别在是,基本没什么区别.ListView与DetailView的区别

model=Atticle#指定了数据表。他的功能相当于取出了Article中的所有数据

template_name="blog/index.html"#指定页面

context_object_name="artcle_list"#listview默认使用object_list作为上下文变量。可使用context_object_name重命名。

get_queryset(self)#默认取出该表所有数据。想要过滤自定义只能在get_queryset()中

get_context_data(self,**kwargs)#这个方法用来添加额外的内容到上下文变量中。

转载至链接:https://my.oschina.net/u/2474096/blog/1920231

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值