开发者

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='/co开发者_StackOverflow社区re/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!


I haven't tested this, but try something like request.GET["key"] = val

Edit: or maybe use request.path_info instead of request.path

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜