Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django, redirect all non-authenticated users to landing page

Tags:

python

django

I have a django website with many urls and views. Now I have asked to redirect all non-authenticated users to a certain landing page. So, all views must check if user.is_authenticated() and return to a new set of landing pages.

Can it be done in a pretty way, instead of messing with my views.py/urls.py that much?

like image 863
xpanta Avatar asked Jan 14 '14 20:01

xpanta


3 Answers

There is a simpler way to do this, just add the "login_url" parameter to @login_required and if the user is not login he will be redirected to the login page. You can find it here

from django.contrib.auth.decorators import login_required

@login_required(login_url='/accounts/login/')
def my_view(request):
    ...
like image 107
AriG Avatar answered Nov 10 '22 15:11

AriG


You can use Middleware.

Something like this will check user auth every request:

class AuthRequiredMiddleware(object):
    def process_request(self, request):
        if not request.user.is_authenticated():
            return HttpResponseRedirect(reverse('landing_page')) # or http response
        return None

Docs: process_request

Also, don't forget to enable it in settings.py

MIDDLEWARE_CLASSES = (
    ...
    'path.to.your.AuthRequiredMiddleware',
)
like image 23
Dmit3Y Avatar answered Nov 10 '22 16:11

Dmit3Y


see the docs for login required decorator

from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...

another option is to add it to your urls.py patterns, see this answer

urlpatterns = patterns('',
    (r'^foo/$', login_required(direct_to_template), {'template': 'foo_index.html'}),
)
like image 16
Guy Gavriely Avatar answered Nov 10 '22 16:11

Guy Gavriely