12

I'm trying to write an abstract parent model in Django which will help me making some slug field from name field for many other child models. It uses trans encoding which works perfect for translitterating form cyrillic to latin letters. Then it uses slugify function from django to remove garbage.

class SlugModel(models.Model):
    class Meta:
        abstract = True

    name = models.CharField(max_length=128, default=u'')
    slug = models.CharField(max_length=128,blank=True)

    def save(self, *args, **kwargs):
        if not self.slug:
            slug = slugify(unicode(self.name).encode('trans'))
        else:
            slug = self.slug
        count = self.__class__.objects.filter(slug = slug).count()
        if count > 1:
            if slug[-2]=='_':
                count = int(slug[-1])
                slug = slug[:-2]
            self.slug = '{0}_{1}'.format(slug,count+1)
        else:
            self.slug = slug
        super(self.__class__, self).save(*args, **kwargs)

    def __unicode__(self):
        return self.name



class Foo(SlugModel):
    pass

The problem occurs when I'm trying to save some Foo object: it causes RuntimeError (maximum recursion depth exceeded). What am I doing wrong? How do I write super(self.__class__, self).save(*args, **kwargs) correctly?

Павел Тявин
  • 2,529
  • 4
  • 25
  • 32
  • 4
    Check out this question (a duplicate) for the answer: http://stackoverflow.com/questions/10948132/abstract-inheritance-in-django-model-causing-max-recursion-depth-error – mjjohnson Nov 18 '12 at 15:05
  • That thread does not have a good answer. – gornvix Sep 11 '20 at 17:13

2 Answers2

13

Ok, I got it. Instead of using super(self.__class__, self).save(*args, **kwargs).

I needed super(SlugModel, self).save(*args, **kwargs).

Thanks to peppergrower.

Williams
  • 4,044
  • 1
  • 37
  • 53
Павел Тявин
  • 2,529
  • 4
  • 25
  • 32
1

Just use super().save(*args, **kwargs).

gornvix
  • 3,154
  • 6
  • 35
  • 74