Home > Enterprise >  Auto generate and save data to SlugField
Auto generate and save data to SlugField

Time:04-27

Hello I have a function to auto generate data for my SlugField but i dont know how to implement a save method to execute it. Ive tried calling the function from the save method but it raises an error of 'instance not defined'. Any suggestions will help. Thanks.

def ran_str_gen(size=6, chars=string.ascii_letters   string.digits):
    return ''.join(secrets.choice(chars) for s in range(size))

def slug_gen(instance, new_slug=None):
    if new_slug is not None:
        slug=new_slug
    else:
        slug = slugify(instance.title)

    op = instance.__class__
    qs_exists = op.objects.filter(slug=slug).exists()
    if not qs_exists:
        new_slug = '{slug}-{ranstr}'.format(slug=slug, ranstr=ran_str_gen())
        return slug_gen(instance, new_slug=new_slug)
    return slug

class Item(models.Model):
    title = models.CharField(max_length=100)
    price = models.FloatField()
    slug = models.SlugField()
    
    def save(self, *args, **kwargs):
        slug_gen()

CodePudding user response:

You should pass the instance (self) to the slug_gen function, store the result in the slug field, and then make a super() call to save the model effectively, so:

class Item(models.Model):
    title = models.CharField(max_length=100)
    price = models.FloatField()
    slug = models.SlugField()
    
    def save(self, *args, **kwargs):
        self.slug = slug_gen(self)
        super().save(*args, **kwargs)

Note: You can make use of django-autoslug [GitHub] to automatically create a slug based on other field(s).


Note: Normally you should not change slugs when the related fields change. As is written in the article Cool URIs don't change [w3.org], URIs are not supposed to change, since these can be bookmarked. Therefore the slug should only be created when creating the object, not when you change any field on which the slug depends.

CodePudding user response:

def save(self, *args, **kwargs):
    self.slug=slug_gen()
  • Related