Generic Django Based Views and Authentication

I am new to Django (since version 1.3). When creating the application from day one, I went with new universal class-based views, using a combination of built-in classes and subclassing them where I needed to be added to the context.

Now my problem is that I need to go back to my views and make them available only for login. All the documentation I found shows how to do this with old functional universal views, but not with a class.

Here is an example class:

class ListDetailView(DetailView): context_object_name = "list" def get_queryset(self): list = get_object_or_404(List, id__iexact=self.kwargs['pk']) return List.objects.all() def get_context_data(self, **kwargs): context = super(ListDetailView, self).get_context_data(**kwargs) context['subscriber_list'] = Subscriber.objects.filter(lists=self.kwargs['pk']) return context 

How to add authentication to new django based classes?

+7
source share
3 answers

There is also an authentication mix option from which you will get your view class. Therefore, using this mixin from brack3t.com :

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

you could then create new “required for authentication” views as follows:

 from django.views.generic import DetailView class MyDetailView(LoginRequiredMixin, DetailView): .... 

without any additional additions. It is very likely that it is not repeated.

+19
source

In the docs section under "> decorating class - based views - if you just want to use the old login_required , etc. that's the way to go.

+6
source

I describe a method to decorate any ListView:

 class MyListView(ListView): decorator = lambda x: x @method_decorator(decorator) def dispatch(self, request, *args, **kwargs): return super(MyListView, self).dispatch(request, *args, **kwargs) 

After writing such a class, you can directly insert any function-based decoder into the URL.

 url(r'^myurl/$', MyListView.as_view(decorator=login_required)) 
+5
source