Create Unique Slug Django
I have a problem with creating unique slugs using django models. I want to allow the admin user to change the slug from the edit page in the admin. When a slug already exists there
Solution 1:
Try this. Didn't test it myself. But it should give you the idea.
import re
defsave(self, *args, **kwargs):
ifnot self.id: # Createifnot self.slug: # slug is blank
self.slug = slugify(self.page_title)
else: # slug is not blank
self.slug = slugify(self.slug)
else: # Update
self.slug = slugify(self.slug)
qsSimilarName = Page.objects.filter(slug__startswith='self.slug')
if qsSimilarName.count() > 0:
seqs = []
for qs in qsSimilarName:
seq = re.findall(r'{0:s}_(\d+)'.format(self.slug), qs.slug)
if seq: seqs.append(int(seq[0]))
if seqs: self.slug = '{0:s}_{1:d}'.format(self.slug, max(seqs)+1)
super(Page, self).save(*args, **kwargs)
Three problems in your code.
- The first
else
means eitherself.id
orself.slug
is NOT blank. So ifself.id
is NOT blank andself.slug
is blank,self.slug
will not get a value. slug_exits == slug
will always be False, becauseslug_exits
is a Model object andslug
is a string. This is why you get the error!- You did a query in the loop, which may cause lots of hits to the DB.
Post a Comment for "Create Unique Slug Django"