view简写 TemplateView.as_view()


view简写 TemplateView.as_view()

https://code.ziqiangxuetang.com/django/django-generic-views.html

1)如果想省略view层,直接在url层返回页面,则在本来要写view函数位置的地方写:TemplateView.as_view(template_name="要渲染的模板文件")

from django.views.generic import TemplateView

url(r"^profile/$", TemplateView.as_view(template_name='account/profile.html'), name="user_profile"),

虽然感觉这种写法貌似破坏了分层的思想,后期如果要给这个url加上其他功能的话还要在写成view文件的形式,要改的较多?

 

2)如果想要给模板传参数的话,需要自己写一个类,继承TemplateView类,并重写他的get_context_data(self, **kwargs)方法:

# 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 

# urls.py中 

 

from  django.conf.urls  import  patterns, url 

 

from  myapp.views  import  HomePageView 

 

urlpatterns  =  patterns('', 

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM