将基于唯一 id 的 slugyfied 字段附加到 Django 中的 URL
有人输入 www.example.com/3/
我有一个带有 charfield 的模型,我可以对它进行 slugify。
class Mymodel(models.Model):
title = models.CharField(max_length=200)
如何在 Django 中将 url 重写为 www.example.com/3/title-of-selected-id
?
我是在 urls.py 还是views.py 中执行此操作?我能想到的就是制作 2 个这样的模式
(r'^mymodels/(?P<mymodel_id>\d+)/(?P<name_slug>[\w-]+)$', 'app.views.detail'),
(r'^mymodels/(?P<mymodel_id>\d+)/$', 'app.views.rewrite'),
然后在我的 app.views.rewrite 中我会得到 mymodel 标题,slugify 它并重定向到第一个 url。但这看起来很脏
Someone inputs www.example.com/3/
I have a model with a charfield that I can slugify.
class Mymodel(models.Model):
title = models.CharField(max_length=200)
How can I rewrite the url as www.example.com/3/title-of-selected-id
in Django?
Do I do it in the urls.py or in the views.py? All I could think of was making 2 patterns like this
(r'^mymodels/(?P<mymodel_id>\d+)/(?P<name_slug>[\w-]+)
And then in my app.views.rewrite I would get the mymodel title, slugify it and redirect to the first url. But this seems awfully dirty
, 'app.views.detail'),
(r'^mymodels/(?P<mymodel_id>\d+)/
And then in my app.views.rewrite I would get the mymodel title, slugify it and redirect to the first url. But this seems awfully dirty
, 'app.views.rewrite'),
And then in my app.views.rewrite I would get the mymodel title, slugify it and redirect to the first url. But this seems awfully dirty
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通过#django irc,有人告诉我重定向方法还不错,我们想不出另一种简单的方法,所以我只是编写了一些似乎有效的代码。
Through #django irc someone told me that the redirect method wasn't bad, and we couldn't think of another easy way so I just coded something up which seems to be working.