Django - 不同类型的用户配置文件

发布于 2024-11-19 21:06:40 字数 533 浏览 4 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

伏妖词 2024-11-26 21:06:41

使用 OneToOneFieldUserlated_name 创建模型。

例如:

class Firm(models.Model):
    user = models.OneToOneField(User, related_name='firm')
    # other fields

class External(models.Model):
    user = models.OneToOneField(User, related_name='external')
    # other fields

然后您可以在 user 中检查此属性是否存在(if hasattr(request.user, 'firm'))并返回正确的实例。我将其放入自定义中间件中,例如设置 request.user_profile 。

Create a model with OneToOneField to User and related_name.

E. g.:

class Firm(models.Model):
    user = models.OneToOneField(User, related_name='firm')
    # other fields

class External(models.Model):
    user = models.OneToOneField(User, related_name='external')
    # other fields

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 set request.user_profile for example.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文