[Fixed]-Class Based View to get user authentication in Django

1👍

You can create a login required mixin to use in your ClassBasedViews like this:

from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required

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

Then use it like @M. Gara suggests (it should be the first thing). Also make sure you have the LOGIN_URL defined in your settings.py

Reference: decorating the class

Alternatively you can choose to decorate the url.

0👍

I dont know whats the context of your ClassBasedView … but you can use the LoginRequiredMixin to require the login before calling your class :

class ServerDeleteView(LoginRequiredMixin, DeleteView):
model = Server
success_url = reverse_lazy('ui:dashboard')

Leave a comment