python C Django中的Slugify字符串
发布时间:2023-12-21 17:43:05 所属栏目:Python 来源:DaWei
导读: 我开发了一个表单,用户添加了他/她的名字和姓氏.
对于用户名(唯一属性),我设计了以下方法:
名字:harrY姓氏:PottEr C >用户名:Harry-Potter
名字:HARRY姓氏:POTTER C >用户名
对于用户名(唯一属性),我设计了以下方法:
名字:harrY姓氏:PottEr C >用户名:Harry-Potter
名字:HARRY姓氏:POTTER C >用户名
我开发了一个表单,用户添加了他/她的名字和姓氏. 对于用户名(唯一属性),我设计了以下方法: 名字:harrY姓氏:PottEr C >用户名:Harry-Potter 名字:HARRY姓氏:POTTER C >用户名:Harry-Potter-1 名字:harrY姓氏:PottEr C >用户名: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)(编辑:4S站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- 一些Python中的二维数组的操作方法
- 在IPython中使用Interactive Shell之外的魔术命令
- 当我运行python manage.py syncdb时,Django避免在
- AIX上的Python:我的选择是什么?
- python – Django REST Framework中的camelCase
- python – “I; 16”图像文件的numpy.array
- 使用带有嵌套查询的python MySQLDB SScursor
- python C 我应该使用GeoDjango来映射平面图吗?
- python – joblib和pickle的不同用例是什么?
- python – igraph:为什么add_edge函数如此缓慢地