Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the url using django process_request .

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?

like image 428
zjm1126 Avatar asked Jun 16 '11 02:06

zjm1126


4 Answers

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.

like image 129
Aryaveer Avatar answered Sep 23 '22 20:09

Aryaveer


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.

like image 22
cwallenpoole Avatar answered Sep 19 '22 20:09

cwallenpoole


Try This

return HttpResponseRedirect('/core/mypage/?key=value')
like image 38
afshin Avatar answered Sep 19 '22 20:09

afshin


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!

like image 33
radtek Avatar answered Sep 22 '22 20:09

radtek