将基于唯一 id 的 slugyfied 字段附加到 Django 中的 URL

发布于 2024-11-24 14:29:39 字数 591 浏览 1 评论 0原文

有人输入 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无声情话 2024-12-01 14:29:39

通过#django irc,有人告诉我重定向方法还不错,我们想不出另一种简单的方法,所以我只是编写了一些似乎有效的代码。

#urls.py
(r'^mymodels/(?P<mymodel_id>\d+)/
, 'app.views.detail'),
(r'^mymodels/(?P<mymodel_id>\d+)/(?P<name_slug>[\w-]+)/
, 'app.views.detail'),

#views.py
def detail(request, mymodel_id, name_slug=None):
    mymodel = get_object_or_404(Mymodel, pk=mymodel_id)

    slug = slugify(mymodel.title)

    if slug == name_slug:
        return HttpResponse("model number %s." % mymodel_id)
    else:
        return redirect(reverse('app.views.detail', args=[mymodel_id, slug]), permanent=True)

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.

#urls.py
(r'^mymodels/(?P<mymodel_id>\d+)/
, 'app.views.detail'),
(r'^mymodels/(?P<mymodel_id>\d+)/(?P<name_slug>[\w-]+)/
, 'app.views.detail'),

#views.py
def detail(request, mymodel_id, name_slug=None):
    mymodel = get_object_or_404(Mymodel, pk=mymodel_id)

    slug = slugify(mymodel.title)

    if slug == name_slug:
        return HttpResponse("model number %s." % mymodel_id)
    else:
        return redirect(reverse('app.views.detail', args=[mymodel_id, slug]), permanent=True)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文