[Fixed]-Django model instance custom method

1👍

You’re not updating the slug of your model. Add self.slug = slug at the end of generate_unique_slug:

def generate_unique_slug(self):
    # your code
    self.slug = slug

0👍

generate_unique_slug neither change any instance attribute nor return anything.

You should change slug in slug = "%s-%d" % (orig[:max_length - len(str(x)) - 1], x) to self.slug = ....

0👍

This answer does not fix your code, but I think it is a good option as it covers multiple cases.

There is a library called uuslug designed to do exactly this. It might be worth checking out.

A example from the repository:

from django.db import models
from uuslug import uuslug

# Override your object's save method with something like this (models.py)
class CoolSlug(models.Model):
    name = models.CharField(max_length=100)
    slug = models.CharField(max_length=200)

    def __unicode__(self):
        return self.name

    def save(self, *args, **kwargs):
        self.slug = uuslug(self.name, instance=self)
        super(CoolSlug, self).save(*args, **kwargs)

name = "john"
c = CoolSlug.objects.create(name=name)
c.save()
print(c.slug) # => "john"

c1 = CoolSlug.objects.create(name=name)
c1.save()
print(c1.slug) # => "john-1"

I also believe you can change slug = models.CharField(max_length=200) to slug = models.SlugField(max_length=200), and it would still work properly.

Edit after comment:

Instead of overriding save, you could do the following:

from uuslug import slugify

class Post(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
    title = models.CharField(max_length=200)
    text = MarkdownField()
    slug = models.SlugField(unique=True, blank=True)
    created = models.DateTimeField(auto_now_add=True)
    published_date = models.DateTimeField(blank=True, null=True)


    def publish(self):
        self.published_date = timezone.now()
        self.slug = slugify(self.title, max_length=self._meta.get_field('slug'))
        self.save()

Does this fix the problem?

Leave a comment