0

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"?

Mojimi
  • 2,561
  • 9
  • 52
  • 116

2 Answers2

2

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")
Brobin
  • 3,241
  • 2
  • 19
  • 35
  • But in this case, how can I send a response to the server if not logged in? My whole web application is dynamic, there is no url redirecting – Mojimi Dec 02 '16 at 20:07
  • Ah, you may want to create your own decorator. I'll edit my post to reflect this. – Brobin Dec 02 '16 at 20:10
  • @Brobin Can you please explain why we need to reinvent the wheel here instead of just using `@login_required`? – ettanany Dec 02 '16 at 20:53
  • @Mojimi is working on a single page application, using each view to just get data from the server in the response. If we used `login_required` it would redirect to the login page instead of giving him the response he needed to render the form on his end. It was simple enough, so the custom decorator was the solution. – Brobin Dec 02 '16 at 21:46
  • @ettanany the comment on the solution below explains in more detail what Mojimi was looking for. – Brobin Dec 02 '16 at 21:49
1

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)?

Community
  • 1
  • 1
Peter DeGlopper
  • 36,326
  • 7
  • 90
  • 83
  • I'm guessing I will have to switch to class views then? Since my web application does not redirect the client to any urls, instead uses AJAX and javascript/jquery to dinamically change the page – Mojimi Dec 02 '16 at 19:55