Django 1.9 or using django-braces
Django 1.9 introduced LoginRequiredMixin , which is used this way:
from django.contrib.auth.mixins import LoginRequiredMixin class MyView(LoginRequiredMixin, View): login_url = '/login/' redirect_field_name = 'redirect_to'
If you are using an older version of django, you can use almost the same mixin from django-braces - the version of Django was based on the version of django-braces. django-braces 1.4.x still supports Django 1.4 , so you can use it with fairly old versions.
Old methods
I found this question during a search in order to decorate class based views, so add an answer for this:
This is described in the documentation section decorating class-based views . There is a urls.py , or you can apply a decorator to the dispatch() method. Examples from the documentation:
Decoration in URL conf
from django.contrib.auth.decorators import login_required, permission_required from django.views.generic import TemplateView from .views import VoteView urlpatterns = patterns('', (r'^about/', login_required(TemplateView.as_view(template_name="secret.html"))), (r'^vote/', permission_required('polls.can_vote')(VoteView.as_view())), )
Class decoration
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)
See the documentation linked above for more details.
Hamish Downer Feb 05 '13 at 14:27 2013-02-05 14:27
source share