简体   繁体   中英

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.

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM