Using mixins, we can automate how the slug field in a model is populated based on some other field in the model.
Slugify mixin -
-
slug_source_field
is name of field whose value will be used to generate the slug. -
slug_target_field
is name of slug field where the generated slug value is to be stored. - Override the
models.Model.save
method to make use ofdjango.utils.text.slugify
onslug_source_field
to generate the slug. - If an entry with same slug exists already, try adding two random characters at the end of the slug and repeat the procedure.
- Set the valid slug value in the
slug_target_field
and letsuper().save(*args, **kwargs)
continue the procedure.
Article model -
- Make use of SlugifyMixin(multiple inheritance)
- Set
slug_source_field
andslug_target_field
That's it. Here's the gist.
Top comments (0)