Django禁用斜杠

时间:2018-07-01 21:41:30

标签: django

我正在使用Django 2.0.6(现在使用开发服务器),并且在自动尾随斜杠附加到URL的问题上遇到了问题。

我的目标是具有如下所示的URL结构:

  • / teams / =>所有团队的索引视图
  • / teams / create =>表单视图以创建一个新团队(请注意缺少尾部斜杠)
  • / teams / xyz / =>弹头xyz的团队的索引视图
  • / teams / xyz / delete =>用于删除团队xyz的表单视图(需要确认等)

问题在于,在Django框架中的某个地方,尾部的斜杠会自动添加到“创建” URL的后面。因此,路由器尝试为“ slug”创建团队加载团队索引页面。显然,一种解决方法是停止使用子弹并使用ID,但这似乎是不必要的让步。

环顾四周,似乎将APPEND_SLASH设置为False应该告诉CommonMiddleware停止添加斜杠,但这无济于事。

有没有一种方法可以轻松完成我的URL方案,如果没有,那么Django的惯用方式是什么?

urls.py:

v = np.random.randn(10)
print(v)
maximum = np.max(v)
minimum = np.min(v)
print(maximum, minimum)
v.index(ma, mi)

settings.py:

from django.urls import path

urlpatterns = [
    path('create', views.create, name='create'),
    path('<slug:team_slug>/', views.view, name='view'),
    path('<slug:team_slug>/invite/', views.invite, name='invite')
]

使用以下内容正确生成链接:

APPEND_SLASH = False

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'debug_toolbar.middleware.DebugToolbarMiddleware',   
]

翻译为:<a class="btn btn-primary" href="{% url 'teams:create' %}">New Team</a>

但是,当用户单击链接时,它似乎立即被重定向到/teams/create

1 个答案:

答案 0 :(得分:0)

  • 在项目目录中创建一个名为common的目录。
  • __init__.py目录中创建redirect.pycommon

    # redirect.py
    
    from django.conf import settings
    from django.core import urlresolvers
    from django import http
    
    '''
    Based on django/middleware/common.py
    
    Django convention is to add trailing slashes to most urls
    This method does the opposite and redirects trailing slashes to the
    no trailing slash url if it exists
    '''
    class RedirectTrailingSlashMiddleware(object):
    
        def process_request(self, request):
            if settings.APPEND_SLASH:
                return 
    
        if '/admin' in request.path:
            settings.APPEND_SLASH = True         
            return
    
        new_url = old_url = request.path
    
        if (old_url.endswith('/')):
            urlconf = getattr(request, 'urlconf', None)
            if (not urlresolvers.is_valid_path(request.path_info, urlconf) and
                urlresolvers.is_valid_path(request.path_info[:-1], urlconf)):
                new_url = new_url[:-1]
                if settings.DEBUG and request.method == 'POST':
                    raise RuntimeError((""
                    "You called this URL via POST, but the URL ends "
                    "in a slash and you have APPEND_SLASH set. Django can't "
                    "redirect to the non-slash URL while maintaining POST data. "
                    "Change your form to point to %s (note no trailing "
                    "slash), or set APPEND_SLASH=True in your Django "
                    "settings.") % (new_url))
    
        if new_url == old_url:
            # No redirects required.
            return
    
        return http.HttpResponsePermanentRedirect(new_url)
    
  • 在您的settings.py中,添加:

    MIDDLEWARE = [
        'common.redirect.RedirectTrailingSlashMiddleware',
        # Add as first element
    ]
    

来源/来源:http://bunwich.blogspot.com/2013/06/django-change-trailing-slash-url.html