Django不区分大小写的网址?

时间:2009-10-04 04:56:11

标签: python django

默认情况下,django的url solver执行区分大小写搜索以解决网址并区分'/ Login'和'login'。我的网址模式如下。

urlpatterns = patterns('',
    (r'^admin/(.*)', admin.site.root),
    (r'^static/(?P<path>.*)$', 'django.views.static.serve',
        {'document_root': settings.STATIC_DOC_ROOT, 'show_indexes': True}),
    (r'^login/$', 'django.contrib.auth.views.login'),
    (r'^logout/$', do_logout),
)

任何人都可以指导我,如何使django urls不区分大小写?

5 个答案:

答案 0 :(得分:87)

只需将(?i)放在每个r'...'字符串的开头,即:

urlpatterns = patterns('',
(r'^(?i)admin/(.*)', admin.site.root),
(r'^(?i)static/(?P<path>.*)$', 'django.views.static.serve',
    {'document_root': settings.STATIC_DOC_ROOT, 'show_indexes': True}),
(r'^(?i)login/$', 'django.contrib.auth.views.login'),
(r'^(?i)logout/$', do_logout),
)

告诉每个RE不区分大小写 - 当然,从此过上幸福的生活! -

答案 1 :(得分:9)

在Django 2.1中,似乎(?i)放在URL正则表达式中的任意位置会导致其忽略大小写。但是,reverse()失败,除非(?i)在正则表达式末尾跟随$

from django.urls import re_path, reverse
from django.shortcuts import render

def home_page(request):
    foo = reverse('home_page')
    return render(request, 'home.html')

urlpatterns = [ re_path(r'home/(?i)', home_page, name='home_page') ]

提高

ValueError: Non-reversible reg-exp portion: '(?i'

但可以使用正则表达式r'home/$(?i)'正常运行。

答案 2 :(得分:2)

Django 2.2更新

根据this ticket

在Django 1.11中弃用了对正则表达式组((?i),(?L),(?m),(?s)和(?u))中的内联标志的支持,并在Django 2.1中删除了

>

在Django 2.2中,将(?i)添加到模式的开头会产生以下异常:

ValueError: Non-reversible reg-exp portion

令人困惑的是,将其添加到末尾会产生以下警告:

DeprecationWarning: Flags not at the start of the expression

The new suggested way在Django中处理大小写敏感的URL是使用custom 404 handler

FWIW,该票证还表明“不区分大小写的URL不是一个好习惯”,但是对此没有任何争论。

PyPi上有一个名为django-icase的软件包,看起来是个不错的选择

答案 3 :(得分:1)

使用Django 2.0(2017年12月发布),使用正则表达式进行网址匹配的推荐方法现在是re_path而不是url

from django.urls import path, re_path
from . import views

urlpatterns = [   
    re_path(r'^(?i)admin/(.*)', admin.site.root),
    re_path(r'^(?i)something/(?P<somestring>\w+)/$', views.something),
    re_path(r'^(?i)login/$', views.login),
    re_path(r'^(?i)logout/$', views.logout),
]

答案 4 :(得分:0)

您也可以从自己的角度进行管理。例如,如果您具有通用的DetailView,则可以覆盖 get_queryset 方法,并将 slug 值设置为小写:

models.py:

from django.db import models
from django.utils.text import slugify


class MyModel(models.Model):
    """MyModel

    """  
    # name attribute is used to generate slug
    name = models.CharField(max_length=25, verbose_name='Name', unique=True)

    slug = models.SlugField(unique=True, verbose_name='Slug')

    # override save method to generate slug
    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        self.slug = slugify(self.name)
        super(MyModel, self).save(force_insert=False, force_update=force_update, using=using, update_fields=update_fields)


views.py:

from django.views import generic


class MyModelDetailView(generic.DetailView):
    """MyModelDetailView

        Detail view of MyObject.
    """

    model = MyModel
    template_name = 'my_models/my_model_detail.html'

    def get_queryset(self):
        try:
            self.kwargs['slug'] = self.kwargs['slug'].lower()
        except Exception as err:
            print(err)
            pass

        queryset = self.model.objects.filter()
        return queryset

urls.py:

from . import views
from django.conf.urls import url

    url(r'^my_model_detail/(?P<slug>[-\w]+)/$', views.MyModelDetailView.as_view(),
        name='my_model_detail'),