DEV Community

Cover image for DRY way of adding slug to models
Tushar Srivastava
Tushar Srivastava

Posted on

DRY way of adding slug to models

Using mixins, we can automate how the slug field in a model is populated based on some other field in the model.

Slugify mixin -

  1. slug_source_field is name of field whose value will be used to generate the slug.
  2. slug_target_field is name of slug field where the generated slug value is to be stored.
  3. Override the models.Model.save method to make use of django.utils.text.slugify on slug_source_field to generate the slug.
  4. If an entry with same slug exists already, try adding two random characters at the end of the slug and repeat the procedure.
  5. Set the valid slug value in the slug_target_field and let super().save(*args, **kwargs) continue the procedure.

Article model -

  1. Make use of SlugifyMixin(multiple inheritance)
  2. Set slug_source_field and slug_target_field

That's it. Here's the gist.

Top comments (0)