Django - 不同类型的用户配置文件
我有一个 Django 应用程序,它允许不同类型的用户:公司、管理员、外部人员等。当然,所有这些都可以使用默认的身份验证系统和组轻松管理。
我的问题是属于不同群体的用户将拥有不同的相关信息 - 例如公司将需要提供一些对私人用户没有意义的商业信息。因此,我需要根据组附加不同类型的配置文件。 (在我的应用程序中,组是互斥的。)
不幸的是,Django 只允许将单个模型作为配置文件附加,并且该模型在 settings.AUTH_PROFILE_MODULE
中声明。在内部,这是通过 User.get_profile() 方法检索的,该方法基本上只是读取该值并执行一些检查,例如模型是否确实存在。
我正在考虑子类化 User
并重写 get_profile()
方法,以便它根据组返回不同的模型。
是否有更简单/更干净的方法来管理不同类型的配置文件?
考虑到引入用户配置文件正是为了避免必须对 User 进行子类化,我的提议似乎有点黑客。
I have a Django application which allows different kinds of users: firms, administrators, external people etc. Of course all of this is easy to manage with the default authentication system and groups.
My problem is that users belonging to different groups will have different related information - for instance firms will need to provide some commercial information that does not make sense for private users. Hence I need to attach different kind of profiles, depending on the group. (In my application groups are mutually exclusive.)
Unfortunately, Django only allows a single model to be attached as a profile, and that model is declared in settings.AUTH_PROFILE_MODULE
. Internally, that is retrieved by the User.get_profile()
method, which basically just reads this value and performs some checks, for instance that the model actually exists.
I was thinking of subclassing User
and overriding the get_profile()
method, so that it returns a different model depending on the group.
Is there a simpler/cleaner way to manage different kind of profiles?
What I am proposing seems a little hack, considering that user profiles were introduced exactly to avoid having to subclass User.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
OneToOneField
到User
和lated_name
创建模型。例如:
然后您可以在
user
中检查此属性是否存在(if hasattr(request.user, 'firm')
)并返回正确的实例。我将其放入自定义中间件中,例如设置 request.user_profile 。Create a model with
OneToOneField
toUser
andrelated_name
.E. g.:
Then you can check the existance of this attributes in
user
(if hasattr(request.user, 'firm')
) and return proper instance. I'd put it in custom middleware, which would setrequest.user_profile
for example.