简体   繁体   中英

django login_required decorator outside view

I am trying to use login_required decorator outside django view. I am using this in a function on my utils.

@login_required
def somefunc():
    #logic

and then I am calling this somefunc() in my view

class MyView(View):
    def get(self, request, *args, **kwargs):
         my_func = Somefunc()

When I do this it says object has no attribute 'user' Whats the issue here ?

login_required is looking for a request object as the first argument to the decorated view function. The request object has a user attribute, which is then checked to see if the user is actually logged in. You can't wrap an arbitrary function with this decorator and expect it to work exactly the same as with an actual view function.

You should add the login_required decorator on the View . This can either be achieved by overriding the dispatch method.

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

You could create your own mixins for achieving this or just use django-braces 's LoginRequiredMixin .

If you want to have this check in the function it might be better to raise a PermissionDenied exception in somefunc .

Either way you will need the request / user in somefunc

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