[Fixed]-Django Models Option Save

1👍

Short answer: this helps you to add slug into new object.

To check if object is new you perform this validation:

if not self.id:

this return True only if self.id is empty. Considering id is primary key it is only possible for new object.

self.slug = slugify(self.name)

Now you convert name field into slug using slugify util:

Converts to ASCII if allow_unicode is False (default). Converts spaces to hyphens. Removes characters that aren’t alphanumerics, underscores, or hyphens. Converts to lowercase. Also strips leading and trailing whitespace.

For example:

slugify(value)

If value is "Joel is a slug", the output will be "joel-is-a-slug".

And finally you call

super(Category, self).save(*args, **kwargs)

to save object.

Leave a comment