如何更改默认的django用户模型以适应我的需要? [英] How to change default django User model to fit my needs?

查看:115
本文介绍了如何更改默认的django用户模型以适应我的需要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认的Django的用户模型有一些字段和验证规则,我不需要。我想使注册尽可能简单,即需要电子邮件或用户名或电话号码 - 所有这些都是唯一的,因此作为用户标识符很好。

The default Django's User model has some fields, and validation rules, that I don't really need. I want to make registration as simple as possible, i.e. require either email or username, or phone number - all those being unique, hence good as user identifiers.

我也不喜欢在Django用户模型中验证的用户名的默认字符集。我想允许任何角色 - 为什么不?

I also don't like default character set for user name that is validated in Django user model. I'd like to allow any character there - why not?

我以前使用用户配置文件django应用程序添加一个配置文件给用户 - 但这次我宁愿使类变得模仿。但是我仍然希望使用 User 类,因为它给了我一个简单的方法来让部分站点仅限于登录用户。

I used user-profile django application before to add a profile to user - but this time I'd rather make the class mimimal. But I still want to use the User class, as it gives me an easy way to have parts of site restricted only for users logged in.

我该怎么办?

推荐答案

而不是直接修改User类或进行子类化,您也可以重新使用现有的字段。

Rather than modify the User class directly or do subclassing, you can also just repurpose the existing fields.

对于一个网站,我使用first_name字段作为用户的公开显示的名称,并将其中的一个版本填入username字段(for在URL中使用)。我写了一个定制的auth后端,以允许人们使用他们的公共名称或他们的电子邮件地址登录,并且在注册时强制执行这两者的唯一性。这与其他可重复使用的应用程序非常相似,并且不会引入额外的表或查询。

For one site I used the "first_name" field as the "publicly displayed name" of a user and stuff a slugified version of that into the "username" field (for use in URLs). I wrote a custom auth backend to allow people to log in using their "public name" or their email address, and I enforce the uniqueness of both of those at registration time. This plays nicely with other reusable apps and doesn't introduce extra tables or queries.

对于另一个网站,我根本不想使用用户名,只有独特的电子邮件。为了满足Django需要一个唯一的用户名,我只是把电子邮件地址和使用它作为用户名(你必须base64编码的哈希来压缩它不超过30个字符)。自定义认证后端允许使用电子邮件登录。

For another site I didn't want usernames at all, just unique emails. In order to satisfy Django's need for a unique username, I just hashed the email address and used that as the username (you have to base64-encode the hash to squeeze it under 30 characters). Custom auth backend to allow login with email.

如果向后兼容性不是问题,我希望看到django有很多改进。 contribaauth和用户模型,使其更灵活。但是现在有很多创造力可以在目前的限制之内做很多事。

If backwards-compatibility weren't an issue, there are a lot of improvements I'd love to see made to django.contrib.auth and the User model to make them more flexible. But there's quite a lot you can do inside the current constraints with a little creativity.

这篇关于如何更改默认的django用户模型以适应我的需要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆