Case Insensitive Query Using Common Views

I would like my URLs to be case insensitive. Adding (? I) to the beginning of regexp in urls.py does not work fully when using generic views.

Here is the URL that I would like to pay attention to:

url(r'^(?i)(?P<year>\d{4})/(?P<month>[az]{3})/(?P<day>\w{1,2})/(?P<slug>[-A-Za-z0-9_]+)/$', BlogDateDetailView.as_view(model=Entry, queryset=Entry.objects.all(), date_field='pub_date', slug_field='slug', )), 

Next job:

 http://mysite.com/2012/jan/24/my-article http://mysite.com/2012/JAN/24/my-article 

Doesn't work (I get 404):

 http://mysite.com/2012/jan/24/My-Article 

I think the reason is that it does not work, because the search query for slug is case sensitive. To make this work, I believe that I need a subclass (not sure if this is the correct term) class SingleObjectMixin(object): since this happens where queryset = queryset.filter(**{slug_field: slug}) . Maybe I need a subclass of get_queryset() .

I would appreciate some recommendations on how I can do this in Django 1.3

+4
source share
1 answer

Case insensitivity in URLs is generally bad. A resource must have only one URL.

However, you can simply use:

 slug_field='slug__iexact' 

But I would instead catch the DoNotExist exception, lower () slug from the URL, retry the request with a new slug and return the redirect to the correct URL. In fact, you can check the uppercase letters before running the first query to avoid unnecessary ones.

This is for you:)

+6
source

Source: https://habr.com/ru/post/1397236/


All Articles