2015年1月29日木曜日
DecoratinginURLconf
Thesimplestwayofdecoratingclass-basedviewsistodecoratetheresultoftheas_view()method.Theeasiest placetodothisisintheURLconfwhereyoudeployyourview: fromdjango.contrib.auth.decoratorsimportlogin_required,permission_required fromdjango.views.genericimportTemplateView from.viewsimportVoteView urlpatterns=[ url(r'^about/',login_required(TemplateView.as_view(template_name="secret.html"))), url(r'^vote/',permission_required('polls.can_vote')(VoteView.as_view())), ] Thisapproachappliesthedecoratoronaper-instancebasis.Ifyouwanteveryinstanceofaviewtobedecorated,you needtotakeadifferentapproach. Decoratingtheclass Todecorateeveryinstanceofaclass-basedview,youneedtodecoratetheclassdefinitionitself.Todothisyouapply thedecoratortothedispatch()methodoftheclass. Amethodonaclassisn'tquitethesameasastandalonefunction,soyoucan'tjustapplyafunctiondecoratortothe method–youneedtotransformitintoamethoddecoratorfirst.Themethod_decoratordecoratortransformsa functiondecoratorintoamethoddecoratorsothatitcanbeusedonaninstancemethod.Forexample: fromdjango.contrib.auth.decoratorsimportlogin_required fromdjango.utils.decoratorsimportmethod_decorator fromdjango.views.genericimportTemplateView classProtectedView(TemplateView): template_name='secret.html' @method_decorator(login_required) defdispatch(self,*args,**kwargs): returnsuper(ProtectedView,self).dispatch(*args,**kwargs) Inthisexample,everyinstanceofProtectedViewwillhaveloginprotection.
登録:
コメントの投稿 (Atom)
0 件のコメント:
コメントを投稿