Search code examples
pythondjangodjango-templatesslug

Why is my overridden save method not running in my django model?


I have this model

class Clinic(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(blank=True)
    website = models.URLField(blank=True)
    phone_number = PhoneNumberField(blank=True)

    slug = models.SlugField(blank=True)
    delivery = models.BooleanField()

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('clinic_detail', kwargs={'slug': self.slug})

    def save(self, *args, **kwargs):
        slug = slugify(self.name)
        super(Clinic, self).save(*args, **kwargs)

and I am trying to have the slug field self populate itself upon creation. I am trying to use the slugify function within the save method to do this but for some reason the save function I definied isn't running when I create a clinic object from the Django admin. When I try to access the clinic object from a list that I generate in this template

<ul>
{% for clinic in object_list %}
    <li><a href="{{clinic.get_absolute_url}}">{{clinic.name}}</a></li>
{% empty %}
    <li>No clinics available</li>
{% endfor %}
</ul>

I get an error because no slug is available so get_absolute_url fails.

If I then go back to the admin and manually add a slug then everything works fine. Why is this happening?


Solution

  • Try this one:

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Clinic, self).save(*args, **kwargs)
    

    But if you want to populate slug only once on creation:

    def save(self, *args, **kwargs):
        if not self.pk:
            self.slug = slugify(self.name)
        super(Clinic, self).save(*args, **kwargs)