Case insensitive urls for Django?

In Django 2.1, it appears that (?i) placed anywhere inside the URL regex will cause it to ignore case. However, reverse() fails unless the (?i) follows the $ at the end of the regex.

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') ]

raises

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

but runs cleanly with the regex r'home/$(?i)'.


Just put (?i) at the start of every r'...' string, i.e.:

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),
)

to tell every RE to match case-insensitively -- and, of course, live happily ever after!-)

Tags:

Python

Django