Amechi
Amechi

Reputation: 800

Auto Populate Slug field django

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)

Upvotes: 17

Views: 21638

Answers (3)

Ahmed Al-Haffar
Ahmed Al-Haffar

Reputation: 552

I think it's better to add a pre_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)```

Upvotes: 4

Luis Gutierrez
Luis Gutierrez

Reputation: 502

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.

Upvotes: 28

an0o0nym
an0o0nym

Reputation: 1516

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.

Upvotes: 1

Related Questions