问题
I don't know if it's possible but I'd like to add few parameters at the end of the URL using middleware. Can it be done without redirect after modyfing requested URL?
ie. user clicks: .../some_link and middleware rewrites it to: .../some_link?par1=1&par2=2
Other way is to modify reponse and replace every HTML link but it's not something I'd like to do.
Thanks
回答1:
I think this really depends on your problem and what exactly you are trying to do.
You cannot change the URL without redirecting the user, as you cannot modify the URL on a page without a reload. Basically a redirect is a response telling the user to move on, there is no way to actually change the URL. Note that even if you do it in something like JavaScript you basically do the same as a redirect, so it can't be done client or server side.
I think it might help if you explain to us why you need to pass this information via the URL. Why not store data in the session?
I guess you could add the data to the request object but that doesn't add it to the URL.
回答2:
class YourRedirectMiddleware:
def process_request(self, request):
redirect_url = request.path+'?par1=1&par2=2'
return HttpResponsePermanentRedirect(redirect_url)
what are you trying to accomplish and why this way?
回答3:
You can do whatever you like in the middleware. You have access to the request object, you can get the URL and redirect to a new one if you want.
My question would be, why do you want to do this? If you need to keep information about the request, the proper place to do this is in the session.
来源:https://stackoverflow.com/questions/1458829/modify-address-in-django-middleware