This is my code :
class MobileMiddleware(object):
def process_request(self, request):
if request.path.startswith('/core/mypage/'):
request.path='/core/mypage/?key=value'
print request.path,'aaaa'
I want to add a param key
when the page url is /core/mypage/
,
and the url of the web browser would be changed to http:www.ss.com/core/mypage/?key=value
However, the url in the browser is not changed.
What can I do?
For googlers - I tested with request.path_info. If you want to change URL in middlware, change request.path_info in process_request.
request.path_info = <change request.path_info>
Please Note that I do not suggest or forbid to use this. I'm just saying if you want to change urls, this is the way you can.
The problem is that HttpRequest.path
is a plain attribute. Changing it does not make any new instructions for the browser. You're probably looking for the redirect method which will actually force the browser to go somewhere else.
Try This
return HttpResponseRedirect('/core/mypage/?key=value')
The request.path_info did not change the url in the browser address bar for me but this redirect did:
from django.shortcuts import redirect
class DomainRedirectMiddleware(object):
def process_request(self, request):
if request.path.startswith('/core/mypage/') and not request.GET:
return redirect('/core/mypage/?key=value') # works!
#request.path_info = '/core/mypage/?key=value' # works, but does not change url in browser address bar
Django also provides a "Redirects App" since Django 1.3, which includes the following middleware: 'django.contrib.redirects.middleware.RedirectFallbackMiddleware' . See the redirects app documentation, it lets you create redirects from the admin interface.
I tried the same redirect using the app and it worked. Cheers!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With