Djangos redirects app doesnt work with URL parameters

2024/4/15 0:56:50

I recently installed Django's default redirects app on my site using the exact instructions specified:

  1. Ensured django.contrib.sites framework is installed.
  2. Added 'django.contrib.redirects' to INSTALLED_APPS.
  3. Added 'django.contrib.redirects.middleware.RedirectFallbackMiddleware' to MIDDLEWARE.
  4. Migrated database using manage.py migrate.

The app works great when my URL is clean, like so:

Redirect setting: /page/ to /redirect/

When I visit https://www.example.com/page/ => redirects to https://www.example.com/redirect/

However, the redirects don't work when URL parameters are appended to the end of my URL, like so:

Redirect setting: /page/ to /redirect/

When I visit https://www.example.com/page/?url_parameter=true => throws Http404 error (page not found)

Ideally, I'd like my redirects to preserve URL parameters, like so:

Redirect setting: /page/ to /redirect/

When I visit https://www.example.com/page/?url_parameter=true => redirects to https://www.example.com/redirect/?url_parameter=true

Is there a way to force the redirects app to preserve URL parameters per the above?

Answer

1.You need to write your own CustomRedirectFallbackMiddleware by subclass django.contrib.redirects.middleware.RedirectFallbackMiddleware and override process_response method of django.contrib.redirects.middleware.RedirectFallbackMiddleware.

custom_redirect_middleware.py

import urlparsefrom django import http
from django.conf import settings
from django.contrib.redirects.models import Redirect
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.redirects.middleware import RedirectFallbackMiddlewareclass CustomRedirectFallbackMiddleware(RedirectFallbackMiddleware):response_gone_class = http.HttpResponseGoneresponse_redirect_class = http.HttpResponsePermanentRedirectdef process_response(self, request, response):if response.status_code != 404:return responsefull_path = request.get_full_path() """ Seperate query parameters and url if full absolute path contains query parameters using python urlparse library       """parsed_url = Noneif "?" in full_path:parsed_url = urlparse.urlparse(full_path)# Now full path contains no query parametersfull_path = parsed_url.pathcurrent_site = get_current_site(request)r = Nonetry:r = Redirect.objects.get(site=current_site, old_path=full_path)except Redirect.DoesNotExist:passif r is None and settings.APPEND_SLASH and not request.path.endswith('/'):try:if parsed_url is not None:r = Redirect.objects.get(site=current_site,old_path= full_path + '/',)else:r = Redirect.objects.get(site=current_site,old_path=request.get_full_path(force_append_slash=True),)except Redirect.DoesNotExist:passif r is not None:if r.new_path == '':return self.response_gone_class()#Adding back the query parameters to redirecting pathif parsed_url is not None:new_path_with_query_params = r.new_path + "?" + parsed_url.queryreturn self.response_redirect_class(new_path_with_query_params)#Handles redirections for urls without query parametersreturn self.response_redirect_class(r.new_path)return response

In this CustomRedirectFallbackMiddleware

i. Simply separated URL parameters from full_absolute_path.

ii. Next got exact redirect_path of separated full_absolute_path form django.contrib.redirects database.

iii. Then appended the URL parameters which separated from full_absolute_path is to redirect_path.

2.Remove 'django.contrib.redirects.middleware.RedirectFallbackMiddleware' from your settings.py and add below line to MIDDLEWARE of settings.py.

# Here base is my Django app name
'base.custom_redirect_middleware.CustomRedirectFallbackMiddleware'

All the bellow cases working very fine.

With no URL parameters.

With one URL paramter.

With more than one URL paramters.

Update: Fixed raising of 404 when URL with no trailing slash.

Hope this helps.

https://en.xdnf.cn/q/73277.html

Related Q&A

get fully qualified method name from inspect stack

I have trouble completing the following function:def fullyQualifiedMethodNameInStack(depth=1):"""The function should return <file>_<class>_<method> for the method in th…

Project Euler #18 - how to brute force all possible paths in tree-like structure using Python?

Am trying to learn Python the Atlantic way and am stuck on Project Euler #18.All of the stuff I can find on the web (and theres a LOT more googling that happened beyond that) is some variation on well …

Is it possible to sniff the Character encoding?

I have a webpage that accepts CSV files. These files may be created in a variety of places. (I think) there is no way to specify the encoding in a CSV file - so I can not reliably treat all of them as …

numpy.empty giving nonempty array

When I create an empty numpy array using foo = np.empty(1) the resulting array contains a float64:>>> foo = np.empty(1) >>> foo array([ 0.]) >>> type(foo[0]) <type numpy.f…

Accessing password protected url from python script

In python, I want to send a request to a url which will return some information to me. The problem is if I try to access the url from the browser, a popup box appears and asks for a username and passwo…

Solving multiple linear sparse matrix equations: numpy.linalg.solve vs. scipy.sparse.linalg.spsolve

I have to solve a large amount of linear matrix equations of the type "Ax=B" for x where A is a sparse matrix with mainly the main diagonal populated and B is a vector. My first approach was …

I want to return html in a flask route [duplicate]

This question already has answers here:Python Flask Render Text from Variable like render_template(4 answers)Closed 6 years ago.Instead of using send_static_file, I want to use something like html(<…

Why doesnt cv2 dilate actually affect my image?

So, Im generating a binary (well, really gray scale, 8bit, used as binary) image with python and opencv2, writing a small number of polygons to the image, and then dilating the image using a kernel. Ho…

How to plot text clusters?

I have started to learn clustering with Python and sklearn library. I have wrote a simple code for clustering text data. My goal is to find groups / clusters of similar sentences. I have tried to plot…

Selenium - Unresponsive Script Error (Firefox)

This question has been asked before, but the answer given does not seem to work for me. The problem is, when opening a page using Selenium, I get numerous "Unresponsive Script" pop ups, refe…