我在两台独立的计算机上安装了两个应用程序。在计算机A上,在urls.py
文件中,我有一行如下:
(r'^cast/$', 'mySite.simulate.views.cast')
该网址适用于mySite.com/cast/
和mySite.com/cast
。但是在计算机B上我有一个类似的URL:
(r'^login/$', 'mySite.myUser.views.login')
出于某种原因,在计算机B上,url mySite.com/login
/会起作用,但mySite.com/login
将会挂起,并且不会像计算机A那样直接返回mySite.com/login/
。是否有我遗漏的内容?两个url.py
文件看起来都与我相同。
答案 0 :(得分:87)
检查settings.py文件中的APPEND_SLASH
设置
答案 1 :(得分:14)
这改善了@Michael Gendin的答案。他的回答用两个单独的URL提供相同的页面。最好让login
自动重定向到login/
,然后将后者作为主页面提供:
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"),
)
答案 2 :(得分:2)
我也有同样的问题。我的解决方案在我的正则表达式的结束行之前放了一个(| /)。
url(r'^artists/(?P[\d]+)(|/)$', ArtistDetailView.as_view()),
答案 3 :(得分:0)
我遇到了同样的问题。在我的情况下,它是来自urls.py中的一些旧版本的陈旧剩余,来自staticfiles之前:
url(r'^%s(?P<path>.*)$' % settings.MEDIA_URL.lstrip('/'),
'django.views.static.serve',
kwargs={'document_root': settings.MEDIA_ROOT}),
MEDIA_URL为空,因此这种模式与所有内容相匹配。
答案 4 :(得分:0)
追加斜杠,无需重定向,在设置Django 2.1中使用它代替CommonMiddleware:
MIDDLEWARE = [
...
# 'django.middleware.common.CommonMiddleware',
'htx.middleware.CommonMiddlewareAppendSlashWithoutRedirect',
...
]
添加到主应用目录 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