【发布时间】:2021-01-23 18:34:33
【问题描述】:
我在一个我没有保存的视频中看到你可以这样做:
12345 是 id 以及实际用于执行查询的位置,this-is-a-tilte 部分在加载页面时自动分配,您实际上可以在那里编写任何您想要的内容,并且仍然会加载页面。
如何在我的路径中设置它,我还需要 SlugField 吗?
【问题讨论】:
标签: python django django-models django-urls slug
我在一个我没有保存的视频中看到你可以这样做:
12345 是 id 以及实际用于执行查询的位置,this-is-a-tilte 部分在加载页面时自动分配,您实际上可以在那里编写任何您想要的内容,并且仍然会加载页面。
如何在我的路径中设置它,我还需要 SlugField 吗?
【问题讨论】:
标签: python django django-models django-urls slug
如果你有一个带有标题的模型:
class Post(models.Model):
title = models.CharField(max_length=128)
# …
您可以制作如下所示的路径:
urlpatterns = [
# …
path('post/<int:pk>/<slug:slug>/', post_detail, name='post_detail'),
]
然后视图可以获取相应的 Post 对象并 slugify 标题。如果 slug 不匹配,它会将其重定向到正确的 slug:
from django.shortcuts import get_object_or_404, redirect
from django.utils.text import slugify
def post_detail(request, pk, slug):
post = get_object_or_404(Post, pk=pk)
post_slug = sluglify(post.title)
if slug != post_slug:
# in case the slug does not match, redirect with the correct slug
return redirect('post_detail', pk=pk, slug=post_slug)
# … logic to render the object …
【讨论】:
您需要SlugField 字段和slugify 函数来从标题自动生成slug。
试试下面的代码
models.py:
from django.db import models
from django.template.defaultfilters import slugify
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
class Post(models.Model):
"""A model holding common fields to Post model."""
slug = models.SlugField(_('slug'), max_length=255,
unique=True, null=True, blank=True,
help_text=_(
'If blank, the slug will be generated automatically '
'from the given title.'
)
)
title = models.CharField(_('title'), max_length=255,
unique=True,
help_text=_('The title of the post.')
)
[..]
def __str__(self):
return self.title
# Where the magic happens ..
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
urls.py:
path('post/<id:pk>/<slug:slug>/', views.post_detail, name='post_detail'),
【讨论】: