Auto Populate Slug field django

删除回忆录丶 提交于 2021-02-18 11:05:39

问题


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() 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.

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)

回答1:


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)

then run:

python manage.py shell

>>>from app.models import Brand
>>>brands = Brands.objects.all()
>>>for brand in brands:
>>>    brand.save()

Also, I would change brand_name var to just name.




回答2:


I think I have an idea, which would do the job, however I am not sure if that would be the best way to do it.

I would use slugify function. I would create the view which - after it was called - would get all model's objects, iterate over them and populate each model's slug field using django.utils.text.slugify function with model's brand_name as a value.




回答3:


I think it's better to add a ore_save signal on the Brand model.

from django.dispatch import receiver
from django.db.models import signals
from django.contrib.auth import get_user_model
from django.utils.text import slugify

@receiver(signals.pre_save, sender=<model name>)
def populate_slug(sender, instance, **kwargs):
    instance.slug = slugify(instance.brand_name)```


来源:https://stackoverflow.com/questions/38963193/auto-populate-slug-field-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!