问题描述
我定义了一个模型,我的数据库中有 100 多个数据条目.我想自动填充一个 slug 字段并看到它显示在管理员中,因为我不想为 100 多个字段添加新条目.
I have a model defined and over 100+ entries of data in my DB. I would like to auto populate a slug field and see it show up in the admin, since adding new entries for 100+ fields is not something I would like to do.
AutoSlug() 字段在我将它添加到我的模型并进行迁移时似乎不起作用,prepopulated_fields = {'slug': ('brand_name',)}
使用它不起作用在我的 admin.py
中,我也尝试将 slug 上的默认字段添加为模型中所需的字段名称,但无济于事,该解决方案不起作用.
AutoSlug() field doesnt seem to be working when I add it to my model and make the migrations, prepopulated_fields = {'slug': ('brand_name',)}
does not work using it within my admin.py
and as well I have tried to add the default field on the slug as my desired field name within the Model but to no avail the solution didnt work.
关于如何预先填充 slug 文件,他们还有其他建议吗?
Is their any other suggestions on how to get the slug filed pre-populated?
class Brand(models.Model):
brand_name = models.CharField(unique=True, max_length=100, blank=True, default="", verbose_name=_('Brand Name'))
slug = models.SlugField(max_length=255, verbose_name=_('Brand Slug'), default=brand_name)
推荐答案
您可以尝试在 Brand 类中添加 save 方法.
You can try adding a save method to the Brand class.
from django.utils.text import slugify
class Brand(models.Model):
...
def save(self, *args, **kwargs):
self.slug = slugify(self.brand_name)
super(Brand, self).save(*args, **kwargs)
然后运行:
python manage.py shell
>>>from app.models import Brand
>>>brands = Brands.objects.all()
>>>for brand in brands:
>>> brand.save()
此外,我会将brand_name var 更改为仅名称.
Also, I would change brand_name var to just name.
这篇关于自动填充 Slug 字段 django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!