Django:使用名字.姓氏创建一个干净的用户名
对于我的网站来说,最好使用 first_name.last_name 形式的标准化用户名,而不是花哨的用户名
。
使用这种用户名创建新用户很简单
username = cleaned_data.get('first_name') + "." + cleaned_data.get('name')
,但是清理这两个字段以便它们包含以下内容的最佳方法是什么:
- 没有空格 ex: Théodore de Banville
- 没有重音 ex: Raphaël LeBlond
- 任何其他有问题的角色
我认为使用 re
和 unidecode
:
username = re.sub(r"\s+", "", username).lowercase
username = unidecode(username)
但这足够了吗?
编辑:这是我当前的解决方案:
fname = unicode(self.cleaned_data['first_name'])
fname = unidecode(fname)
fname = slugify(fname)
name = unicode(self.cleaned_data['last_name'])
name = unidecode(name)
name = slugify(name)
username = fname + "." + name
instead of a fancy username
, it would be better for my website to have a normalized username in the form first_name.last_name.
It is simple to create the new user with this kind of username
username = cleaned_data.get('first_name') + "." + cleaned_data.get('name')
but what is the best way to clean both fields in order that they contain:
- no spaces ex: Théodore de Banville
- no accents ex: Raphaël LeBlond
- any other problematic characters
I thought of using re
and unidecode
:
username = re.sub(r"\s+", "", username).lowercase
username = unidecode(username)
but is this enought?
EDIT: here is my current solution:
fname = unicode(self.cleaned_data['first_name'])
fname = unidecode(fname)
fname = slugify(fname)
name = unicode(self.cleaned_data['last_name'])
name = unidecode(name)
name = slugify(name)
username = fname + "." + name
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这主要是
slugify()
确实如此,但是使用unidecode()
是一个巨大的改进。我要做的唯一更改是首先应用unidecode()
,然后删除空格。That's mostly what
slugify()
does, but the use ofunidecode()
is a huge improvement. The only change I'd make is to applyunidecode()
first, then remove the spaces.