gpt4 book ai didi

python - 在 Django 中对字符串进行 Slugify

转载 作者:太空狗 更新时间:2023-10-29 21:37:39 24 4
gpt4 key购买 nike

我开发了一个表单,用户可以在其中添加他/她的 first namelast name

对于 username(unique 属性),我设计了以下方法:

FirstName:harrY LastName:PottEr --> username:Harry-Potter

FirstName:HARRY LastName:POTTER --> username:Harry-Potter-1

FirstName:harrY LastName:PottEr --> username:Harry-Potter-2

等等..

这是我的函数定义:

def return_slug(firstname, lastname):
u_username = firstname.title()+'-'+lastname.title() //Step 1
u_username = '-'.join(u_username.split()) //Step 2
count = User.objects.filter(username=u_username).count() //Step 3
if count==0:
return (u_username)
else:
return (u_username+'-%s' % count)

在实现第 3 步 之前,我不知道该做什么。我应该在哪里放置 [:len(u_username)] 来比较字符串?

编辑:

如果 Harry-Potter 有多个实例,则应用此方法,解决最后添加整数的问题。我的问题是:我将如何检查附加到 Harry-Potter 的最后一个整数是什么?

最佳答案

试试这个:

from django.utils.text import slugify

def return_slug(firstname, lastname):

# get a slug of the firstname and last name.
# it will normalize the string and add dashes for spaces
# i.e. 'HaRrY POTTer' -> 'harry-potter'
u_username = slugify(unicode('%s %s' % (firstname, lastname)))

# split the username by the dashes, capitalize each part and re-combine
# 'harry-potter' -> 'Harry-Potter'
u_username = '-'.join([x.capitalize() for x in u_username.split('-')])

# count the number of users that start with the username
count = User.objects.filter(username__startswith=u_username).count()
if count == 0:
return u_username
else:
return '%s-%d' % (u_username, count)

关于python - 在 Django 中对字符串进行 Slugify,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16696886/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com