[英]create unique slug django
I have a problem with creating unique slugs using django models. 我在使用Django模型创建唯一的子弹时遇到问题。 I want to allow the admin user to change the slug from the edit page in the admin.
我想允许管理员用户从管理员的编辑页面更改子弹。 When a slug already exists there should be "slug + _1", "slug + _2" etc. Also when a new page is created and there is no slug given the slug should be the page title.
如果已存在段,则应该有“段+ _1”,“段+ _2”等。同样,在创建新页面并且没有段的情况下,段应该是页面标题。 I have this code but for some reason the admin keeps saying "Page with this Slug already exists."
我有此代码,但出于某些原因,管理员一直说“带有此子弹的页面已存在”。 when I add a page with a slug that already exists.
当我添加带有已存在的子弹的页面时。 Hope somebody can help me
希望有人能帮助我
def save(self, *args, **kwargs):
if not self.id and not self.slug:
self.slug = slugify(self.page_title)
else:
self.slug = slugify(self.slug)
slug_exists = True
counter = 1
slug = self.slug
while slug_exists:
try:
slug_exits = Page.objects.get(slug=slug)
if slug_exits == slug:
slug = self.slug + '_' + str(counter)
counter += 1
except:
self.slug = slug
break
super(Page, self).save(*args, **kwargs)
Try this. 尝试这个。 Didn't test it myself.
我自己没有测试。 But it should give you the idea.
但这应该可以给您这个想法。
import re
def save(self, *args, **kwargs):
if not self.id: # Create
if not 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. 您的代码中的三个问题。
else
means either self.id
or self.slug
is NOT blank. else
意味着要么self.id
或self.slug
不是空白。 So if self.id
is NOT blank and self.slug
is blank, self.slug
will not get a value. self.id
不为空且self.slug
为空,则self.slug
将不会获得值。 slug_exits == slug
will always be False, because slug_exits
is a Model object and slug
is a string. slug_exits == slug
始终为False,因为slug_exits
是一个Model对象,而slug
是一个字符串。 This is why you get the error!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.