Auto Populate Slug field django

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)```

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.


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.