How to apply decorator do dispatch method in class-based views Django

天涯浪子 提交于 2019-12-04 14:06:18
schillingt

You can use the decorator method_decorator as shown here in the docs.

From the docs:

from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView

class ProtectedView(TemplateView):
    template_name = 'secret.html'

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(ProtectedView, self).dispatch(*args, **kwargs)

Or you can do it in your urls.py:

from django.conf.urls import patterns
from django.contrib.auth.decorators import login_required
from myapp.views import MyView

urlpatterns = patterns('',
    (r'^about/', login_required(MyView.as_view())),
)

Update:

As of Django 1.9, you can now use the method decorator at the class level. You will need to pass the name of the method to be decorated. So there's no need to override dispatch just to apply the decorator.

Example:

@method_decorator(login_required, name='dispatch')
class ProtectedView(TemplateView):
    template_name = 'secret.html'

Moreover, you can define a list or tuple of decorators and use this instead of invoking method_decorator() multiple times.

Example(the two classes below are the same):

decorators = [never_cache, login_required]

@method_decorator(decorators, name='dispatch')
class ProtectedView(TemplateView):
    template_name = 'secret.html'

@method_decorator(never_cache, name='dispatch')
@method_decorator(login_required, name='dispatch')
class ProtectedView(TemplateView):
    template_name = 'secret.html'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!