简体   繁体   中英

Django generic authentication in views

How can I avoid needing to have this piece of code in every view function :

if request.user.is_authenticated():

    return HttpResponse("OK")
else:

    return HttpResponse("Load_Login_Form")

But instead execute it everytime/before an url/view is "called"?

I would use a custom method decorator to return your login response if the user is not yet logged in. Something like this:

# decorators.py
from django.http import HttpResponse


def check_login(view):
    def wrap(request, *args, **kwargs):
        if not request.user.is_authenticated():
            return HTTPResponse("Load_Login_Form")
        return view(request, *args, **kwargs)
    return wrap

Then you simply import that to your views file and add it before each view that you want to protect

# views.py
from django.http import HttpResponse
from .decorators import check_login


@check_login
def ok_view(request):
    return HttpResponse("OK")

The authentication package provides decorators and mixins to support this. The decorators are easy to use if you want to redirect to a login page for unauthenticated users, the mixins are more flexible in case you want to do something else but require you to use class-based views.

If you want to apply this behavior to your entire site rather than decorate or inherit in the views that require login, (except, one assumes, for some whitelisted pages like the login) there are examples of middleware that can support that in this old question: Django: How can I apply the login_required decorator to my entire site (excluding static media)?

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