没有尾部斜杠的 django urls 不会重定向

我在两台不同的电脑上找到了两个应用程序。在计算机 A 中,在 urls.py文件中有一行如下:

(r'^cast/$', 'mySite.simulate.views.cast')

这个 URL 将同时适用于 mySite.com/cast/mySite.com/cast。但是在计算机 B 上,我有一个类似的网址写成:

(r'^login/$', 'mySite.myUser.views.login')

由于某种原因,在计算机 B 上的 url mySite.com/login/将工作,但 mySite.com/login将挂起,不会直接回到 mySite.com/login/就像它将在计算机 A 上?两个 url.py文件看起来一模一样。

90794 次浏览

check your APPEND_SLASH setting in the settings.py file

more info in the django docs

Or you can write your urls like this:

(r'^login/?$', 'mySite.myUser.views.login')

The question sign after the trailing slash makes it optional in regexp. Use it if for some reasons you don't want to use APPEND_SLASH setting.

I've had the same problem. In my case it was a stale leftover from some old version in urls.py, from before staticfiles:

url(r'^%s(?P<path>.*)$' % settings.MEDIA_URL.lstrip('/'),
'django.views.static.serve',
kwargs={'document_root': settings.MEDIA_ROOT}),

MEDIA_URL was empty, so this pattern matched everything.

I've had the same problem too. My solution was put an (|/) before the end line of my regular expression.

url(r'^artists/(?P[\d]+)(|/)$', ArtistDetailView.as_view()),

This improves on @Michael Gendin's answer. His answer serves the identical page with two separate URLs. It would be better to have login automatically redirect to login/, and then serve the latter as the main page:

from django.conf.urls import patterns
from django.views.generic import RedirectView


urlpatterns = patterns('',
# Redirect login to login/
(r'^login$', RedirectView.as_view(url = '/login/')),
# Handle the page with the slash.
(r'^login/', "views.my_handler"),
)

Append slash without redirect, use it instead of CommonMiddleware in settings, Django 2.1:

MIDDLEWARE = [
...
# 'django.middleware.common.CommonMiddleware',
'htx.middleware.CommonMiddlewareAppendSlashWithoutRedirect',
...
]

Add to your main app directory middleware.py:

from django.http import HttpResponsePermanentRedirect, HttpRequest
from django.core.handlers.base import BaseHandler
from django.middleware.common import CommonMiddleware
from django.conf import settings




class HttpSmartRedirectResponse(HttpResponsePermanentRedirect):
pass




class CommonMiddlewareAppendSlashWithoutRedirect(CommonMiddleware):
""" This class converts HttpSmartRedirectResponse to the common response
of Django view, without redirect.
"""
response_redirect_class = HttpSmartRedirectResponse


def __init__(self, *args, **kwargs):
# create django request resolver
self.handler = BaseHandler()


# prevent recursive includes
old = settings.MIDDLEWARE
name = self.__module__ + '.' + self.__class__.__name__
settings.MIDDLEWARE = [i for i in settings.MIDDLEWARE if i != name]


self.handler.load_middleware()


settings.MIDDLEWARE = old
super(CommonMiddlewareAppendSlashWithoutRedirect, self).__init__(*args, **kwargs)


def process_response(self, request, response):
response = super(CommonMiddlewareAppendSlashWithoutRedirect, self).process_response(request, response)


if isinstance(response, HttpSmartRedirectResponse):
if not request.path.endswith('/'):
request.path = request.path + '/'
# we don't need query string in path_info because it's in request.GET already
request.path_info = request.path
response = self.handler.get_response(request)


return response

In some cases, we have issues when some of our users call API with different endings. Usually, our users use Postman for that and are not worried about slash at the endpoint. As result, we receive issue requests in support, because users forgot to append a slash / at the end of POST requests.

We solved it by using a custom middleware that works for us in Django 3.2+ and Django 4.0+. After that, Django may handle any POST/PUT/DELETE requests to your API with slash or without them. With this middleware unneeded to change APPEND_SLASH property in settings.py

So, in the settings.py need to remove your current 'django.middleware.common.CommonMiddleware' and insert new middleware. Make sure, you change your_project_name in my example below on your real project name.

MIDDLEWARE = [
...
# 'django.middleware.common.CommonMiddleware',
'your_project_name.middleware.CommonMiddlewareAppendSlashWithoutRedirect',
...
]

Add to your main app directory middleware.py:

from django.http import HttpResponsePermanentRedirect, HttpRequest
from django.core.handlers.base import BaseHandler
from django.middleware.common import CommonMiddleware
from django.utils.http import escape_leading_slashes
from django.conf import settings




class HttpSmartRedirectResponse(HttpResponsePermanentRedirect):
pass




class CommonMiddlewareAppendSlashWithoutRedirect(CommonMiddleware):
""" This class converts HttpSmartRedirectResponse to the common response
of Django view, without redirect. This is necessary to match status_codes
for urls like /url?q=1 and /url/?q=1. If you don't use it, you will have 302
code always on pages without slash.
"""
response_redirect_class = HttpSmartRedirectResponse


def __init__(self, *args, **kwargs):
# create django request resolver
self.handler = BaseHandler()


# prevent recursive includes
old = settings.MIDDLEWARE
name = self.__module__ + '.' + self.__class__.__name__
settings.MIDDLEWARE = [i for i in settings.MIDDLEWARE if i != name]


self.handler.load_middleware()


settings.MIDDLEWARE = old
super(CommonMiddlewareAppendSlashWithoutRedirect, self).__init__(*args, **kwargs)


def get_full_path_with_slash(self, request):
""" Return the full path of the request with a trailing slash appended
without Exception in Debug mode
"""
new_path = request.get_full_path(force_append_slash=True)
# Prevent construction of scheme relative urls.
new_path = escape_leading_slashes(new_path)
return new_path


def process_response(self, request, response):
response = super(CommonMiddlewareAppendSlashWithoutRedirect, self).process_response(request, response)


if isinstance(response, HttpSmartRedirectResponse):
if not request.path.endswith('/'):
request.path = request.path + '/'
# we don't need query string in path_info because it's in request.GET already
request.path_info = request.path
response = self.handler.get_response(request)


return response

This answer may look similar to Max Tkachenko answer. But his code didn't work for me in the latest versions of Django.