Django 3.2:autoslugfield返回无

2024-06-16 10:31:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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字段始终为“无”


Tags: instancefrom模型selftruegetreturntitle
1条回答
网友
1楼 · 发布于 2024-06-16 10:31:20

奇怪的是它不起作用。我还认为它的工作方式与您的工作方式相同,但您是否尝试过使用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)

相关问题 更多 >