[Answer]-Middleware is not work expected

1πŸ‘

βœ…

Is this the one you are talking:

class AutoLogout:
    def process_request(self, request):
        if not request.user.is_authenticated() :
            return HttpResponseRedirect(reverse('app_name:url_name'))

        try:
            if datetime.now() - request.session['last_touch'] > timedelta( 0, settings.AUTO_LOGOUT_DELAY * 60, 0):
                auth.logout(request)
                del request.session['last_touch']
                return HttpResponseRedirect(reverse('app_name:url_name'))
        except KeyError:
            pass

        request.session['last_touch'] = datetime.now()

decorators.py

from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect

def login_check(view_func):
    def _wrapped_view_func(request, *args, **kwargs):
        if not request.user.is_authenticated:
            //return to home page url
            return HttpResponseRedirect(reverse('app_name:url_name'))
        return view_func(request, *args, **kwargs)
    return _wrapped_view_func

After you create decorators.py, update your view like this:

from app_name.decorators import login_check

@login_check
def view_name(request):
    .........

The user will not be allow to go to that page if not authenticated.

πŸ‘€catherine

Leave a comment