我开发了一个表单,用户可以在其中添加他/她的first name和last name。
对于username (一个unique属性),我设计了以下方法:
FirstName:harrY LastName:PottEr -> username:哈利波特
FirstName:哈利LastName:波特-> username:哈利波特1
FirstName:harrY LastName:PottEr -> username:哈利波特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)在Step 3实现之前,我不知道该做什么。我应该把[:len(u_username)]放在哪里来比较字符串呢?
编辑:
如果存在多个Harry-Potter实例,则应用此方法,解决最后添加整数的问题。我的问题是:如何检查最后一个整数是如何附加到Harry-Potter中的。
发布于 2013-05-22 16:37:38
试试这个:
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)https://stackoverflow.com/questions/16696886
复制相似问题