如何在Django中生成“假”子弹

问题描述

我在视频中看到没有保存,您可以执行以下操作:

www.mysite.com/post/12345/this-is-a-title

12345是id的地方,实际上是用于执行查询的地方,this-is-a-tilte部分在加载页面时会自动分配,您实际上可以在其中写任何内容,并且仍然会加载页面

如何在路径中设置它,我还需要一个SlugField吗?

解决方法

您将需要SlugField字段和slugify函数来根据标题自动生成子弹。

尝试下面的代码

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'),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'),
,

如果您的模型带有标题:

class Post(models.Model):
    title = models.CharField(max_length=128)
    # …

您可以创建如下路径:

urlpatterns = [
    # …
    path('post/<int:pk>/<slug:slug>/',post_detail,]

然后,视图可以获取相应的Post对象并隐藏标题。如果该子弹不匹配,它将重定向到正确的子弹:

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 …