使用通用视图的不区分大小写的查询
我希望我的网址不区分大小写。使用通用视图时,将 (?i) 添加到 urls.py 中的正则表达式的开头并不能完全起作用。
这是我想关注的网址:
url(r'^(?i)(?P<year>\d{4})/(?P<month>[a-z]{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',
)),
以下工作:
http://mysite.com/2012/jan/24/my-article
http://mysite.com/2012/JAN/24/my-article
以下不起作用(即我得到 404):
http://mysite.com/2012/jan/24/My-Article
我认为它不起作用的原因是因为 slug 的查找查询区分大小写。为了完成这项工作,我相信我需要子类化(不确定这是否是正确的术语)class SingleObjectMixin(object):
,因为这是 queryset = queryset.filter(* *{slug_field: slug})
发生了。也许我应该子类化get_queryset()
。
我希望得到一些有关如何在 django 1.3 中干净地完成此操作的指导
I would like my urls to be case insensitive. Adding (?i) to the beginning of the regexp in urls.py does not work completely when using generic views.
Here is the url that I'd like to focus on:
url(r'^(?i)(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/(?P<slug>[-A-Za-z0-9_]+)/
The following work:
http://mysite.com/2012/jan/24/my-article
http://mysite.com/2012/JAN/24/my-article
The following does not work (i.e I get a 404):
http://mysite.com/2012/jan/24/My-Article
I think the reason it does not work is because the lookup query for the slug is case sensitive. In order to make this work, I believe I need to subclass (not sure if this is the right term) class SingleObjectMixin(object):
since this is where queryset = queryset.filter(**{slug_field: slug})
happens. Perhaps I should subclass get_queryset()
.
I'd appreciate some guidance on how I could do this cleanly in django 1.3
, BlogDateDetailView.as_view(model=Entry,
queryset=Entry.objects.all(),
date_field='pub_date',
slug_field='slug',
)),
The following work:
The following does not work (i.e I get a 404):
I think the reason it does not work is because the lookup query for the slug is case sensitive. In order to make this work, I believe I need to subclass (not sure if this is the right term) class SingleObjectMixin(object):
since this is where queryset = queryset.filter(**{slug_field: slug})
happens. Perhaps I should subclass get_queryset()
.
I'd appreciate some guidance on how I could do this cleanly in django 1.3
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
URL 中不区分大小写通常是一件坏事。一项资源实际上应该只有一个 URL。
但是,您可以只使用:
但是,我会捕获DoesNotExist异常,lower()来自URL的slug,使用新的slug再次尝试查询并返回到正确URL的重定向。实际上,您可以在运行第一个查询之前检查大写字母,以避免运行不必要的字母。
由你决定 :)
Case-insensitivity in URLs is generally a bad thing. A resource should only really have one URL.
However, you can just use:
But, I would instead catch the DoesNotExist exception, lower() the slug from the URL, try the query again with the new slug and return a redirect to the correct URL. You could actually check for uppercase letters before running the first query to avoid running unnecessary ones.
It's up to you :)