【问题标题】:django 3.2 : autoslugfield return Nonedjango 3.2:autoslugfield 返回无
【发布时间】:2021-07-28 16:52:34
【问题描述】:

我在 django3.2 上安装了 autoslug

我的模特:

from autoslug import AutoSlugField

class Courses(models.Model):
    title = models.CharField(max_length=100, null=True)
    description = models.TextField(null=True)
    image = models.ImageField(upload_to=get_dynamic_path_course, null=True)
    price = models.PositiveIntegerField(null=True)

    slug = AutoSlugField(populate_from=get_populate_from, null=True, blank=True, allow_unicode=True)

    def __str__(self):
        return '%d :  %s => ,  %s' % (self.id, self.title, self.slug)

功能:

def get_populate_from(instance):
    return instance.title.replace(' ', '_')

我的问题:

slug 字段总是无

【问题讨论】:

    标签: python django django-models python-3.8 slug


    【解决方案1】:

    奇怪的是它不起作用。我也认为它的工作方式与您一样,但是您是否尝试过使用 lambda?

    slug = AutoSlugField(populate_from=lambda instance: instance.title.replace(' ', '_'), null=True, blank=True, allow_unicode=True)
    

    另一种选择是像这样更改 slugify 函数:

    def custom_slugify(value):
        return value.replace(' ', '_')
    
    slug = AutoSlugField(populate_from='title', slugify=custom_slugify, null=True, blank=True, allow_unicode=True)
    

    【讨论】:

    • 当我使用 lambda 时出现错误:无法序列化函数 lamba
    • 当我使用 slogify - slug 没有
    猜你喜欢
    • 2014-10-31
    • 2013-01-05
    • 1970-01-01
    • 2013-09-10
    • 2014-05-14
    • 2020-08-09
    • 2016-03-22
    • 1970-01-01
    • 2022-07-17
    相关资源
    最近更新 更多