django only redirecting to base url not absolute uri

I am trying to redirect back to the url that made a request before request was made to an external login service, using amiddleware.

The solution I currently have only redirects to the base url (

When I go to, I am redirected to

https://external_login/login?abc=def&the_url= which is correct, after a successful login, I am redirected to instead of

Is there any way I can redirect to the calling URL before temporarily redirect to external login?


class AttemptRedirect(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        url = request.build_absolute_uri()
        if 'username' not in request.session:
            if request.GET.get('xyz'):
                validate = 'https://external_login/validate?abc=def&xyz={}&the_url={}'.format(request.GET.get('xyz'), url)

                req = urllib.request.Request(validate)
                gcontext = ssl.SSLContext()
                response = urllib.request.urlopen(req, context=gcontext).read()
                result = response.decode('utf-8')

                if result[0:3] == 'yes':
                    request.session['username'] = result[3:]

                    new_url = urlparse(request.build_absolute_uri())
                    query = parse_qs(u.query)
                    query.pop('xyz', None)
                    new_url = new_url._replace(query=urlencode(query, True))
                    new_url = urlunparse(new_url)

                    return redirect(new_url)
                return redirect("https://external_login/login?abc=def&the_url={}".format(url))
            response = self.get_response(request)
            return response