如何同时使用Django Auth和DRF Token auth?

时间:2020-11-11 17:23:17

标签: python django authentication django-rest-framework

我正在构建一个Django Web应用程序,我想要两件事:

  • 使用Django的内置用户模型来使用Django的Admin应用(商店所有者)
  • 在将要命名为“客户”(商店客户)的自定义用户模型上使用DRF的令牌身份验证

如何为上述目的保留两个身份验证系统。根据我的阅读,每个人都要求重写User模型,但我不想这样做。相反,我想保留两者。我应该采取什么策略?

PS:可能是我,但是我无法在DRF的文档中找到任何解决方案。如果有的话,请指向正确的方向。

1 个答案:

答案 0 :(得分:0)

Django确实提供了使用custom user model的选项。但是您只能有一个用户模型。

此过程非常简单,创建继承django.contrib.auth.models.AbstractUser的自己的模型,并指定AUTH_USER_MODEL设置变量。 Django管理员可以很好地使用“自定义用户模型”概念。 DRF令牌模型也将settings.AUTH_USER_MODEL var用于其OneToOne关系。因此,这可能是一个可行的解决方案。

要分离出用户类型,可以使用具有代表用户类型的选择的char字段,也可以使用现有的Django组机制。但是,在两种情况下,您仍然只能拥有一个用户模型。

有关任何特定的详细信息,您可以将OneToOne关系与存储额外信息的不同模型联系起来。

类似的事情,

from django.contrib.auth.models import AbstractUser
from model_utils.choices import Choices   # Useful package
from django.utils.functional import cached_property


class User(AbstractUser):
    USER_TYPES = Choices(
        ("store_owner", "Store Owner"),
        ("customer", "Customer"),
    )
    ...hack...
    user_type = models.CharField(choices=USER_TYPES)
    ...hack...

    @cached_property
    def is_store_owner(self):
        return (
            self.user_type == self.USER_TYPES.store_owner 
            and self.store_owner is not None
        )

    @cached_property
    def is_customer(self):
        return (
            self.user_type == self.USER_TYPES.customer 
            and self.customer is not None
        )


class StoreOwner(models.Model):
    user = models.OneToOneField(
        "yourapp.User", 
        related_name="store_owner",
    )
    # ...extra store owner details...


class Customer(models.Model):
    user = models.OneToOneField(
        "userapp.User",
        related_name="customer",
    )
    # ...extra customer details...