1

I am trying to redirect to login page with return url through a middleware .

I am getting this error so can anyone answer the question why i am getting this error and how to solve this error

from django.shortcuts import redirect
def auth_middleware(get_response):
     def middleware(request):
        print("Middleware")
        return_url = request.META['PATH_INFO']
        if not request.session.get('user_id'):
            return redirect(f'account:login?return_url={return_url}')
        response = get_response(request)
        return response

    return middleware

1 Answers1

0

Django will make a redirect to account:login?return_url=some_url, but the browser does not understand this: since it sees a URL that starts with account:, it assumes that account: is the protocol.

We can reverse the view with reverse(…) [Django-doc]:

from django.urls import reverse
from django.http import HttpResponseRedirect

def auth_middleware(get_response):
     def middleware(request):
        print("Middleware")
        return_url = request.META['PATH_INFO']
        if not request.session.get('user_id'):
            return HttpResponseRedirect(f'{reverse("account:login")}?return_url={return_url}')
        response = get_response(request)
        return response

    return middleware

or you can make a decorator with:

from django.urls import reverse
from django.http import HttpResponseRedirect
from functools import wraps

def auth_decorator(view):
    @wraps(view)
    def wrapper(request, *args, **kwargs):
        print("Middleware")
        return_url = request.META['PATH_INFO']
        if not request.session.get('user_id'):
            return HttpResponseRedirect(f'{reverse("account:login")}?return_url={return_url}')
        return view(request, *args, **kwargs)

    return wrapper
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Thank you it solved my problem. But how can i use this middleware in url that has id attached to it . 'path('dashboard/pages-profile/', auth_middleware(Profile.as_view()), name='profile'),' Got this error: **auth_middleware..middleware() got an unexpected keyword argument 'user_id'** – Bibek Karna Nov 25 '21 at 05:27
  • @BibekKarna: you are using the middleware as a decorator for your views. But that does not make much sense: middleware is only given the request object, not the URL parameters. – Willem Van Onsem Nov 25 '21 at 07:17
  • Then how can i apply this in my view so that user that is not logged in cannot access that page. – Bibek Karna Nov 25 '21 at 07:59
  • @BibekKarna: see edit to use this as a decorator. – Willem Van Onsem Nov 25 '21 at 08:10
  • Thank you so much for your help.It solved my problem – Bibek Karna Nov 25 '21 at 12:09