reverse() does not add SCRIPT_NAME to the returned URL if called from middleware modules
|Reported by:||ElliottM||Owned by:||Malcolm Tredinnick|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
Description (last modified by )
For example, take the following middleware.py file, with one example middleware thing that redirects you to the login page if you are not logged in:
login_url=reverse('login') class LoginMiddleware(): def process_request(self, request): if(request.user.is_anonymous() and request.path!=login_url): #force login return HttpResponseRedirect(login_url+'?next='+request.path)
In this case, login_url will be correct except for the fact that it will be missing the SCRIPT_NAME. Putting the reverse() call inside the process_request function solves the problem, but it makes no sense at all to call that reverse function for every request when it can be called once at server startup.
The cause is in django.core.handles.wsgi and django.core.handlers.modpython
if self._request_middleware is None: self.load_middleware() set_script_prefix(req.get_options().get('django.root', ''))
As you can see, "set_script_prefix" is called AFTER middleware is loaded, so the script name is still unset when reverse() is called in the middleware above. Moving the set_script_prefix call above the load_middleware function solves the problem.
Change History (9)
comment:1 Changed 8 years ago by
|Summary:||reverse() does not add SCRIPT_NAME to the returned URL if called from modules that contain middleware → reverse() does not add SCRIPT_NAME to the returned URL if called from middleware modules|
comment:2 follow-up: 7 Changed 8 years ago by
|Owner:||changed from nobody to Malcolm Tredinnick|