Search code examples
djangodjango-viewsdjango-validation

How to use django login_required method


class HomePage(TemplateView):

    template_name = 'obs/homepage.html'

I want to make this view accessible to only logged in users. How can I do that? I've seen django documentation but it was for functions.


Solution

  • I tend to setup a mixin to use in view, something like this;

    from django.contrib.auth.decorators import login_required
    from django.utils.decorators import method_decorator
    from django.views.generic import TemplateView
    
    class LoginRequiredMixin(object):
        @method_decorator(login_required)
        def dispatch(self, *args, **kwargs):
            return super(LoginRequiredMixin, self).dispatch(*args, **kwargs)
    
    class HomePage(LoginRequiredMixin,TemplateView):
        template_name = 'obs/homepage.html'