【问题标题】:Multi-tenant schema with django使用 django 的多租户模式
【发布时间】:2019-06-23 22:19:47
【问题描述】:

我是使用 django 处理多租户模式的新手。我已经按照下面的链接https://django-tenant-schemas.readthedocs.io/en/latest/install.html

当我创建客户端对象时,会创建单独的租户模式,这很好。但关注的用户不是在单独的租户模式中创建的,它只在公共模式中创建。 我的看法:

def registration(request):
   form = RegistrationForm()
   if request.method == 'POST': # Post method
      company_name = request.POST['company_name']
      website = request.POST['website']
      username = request.POST['username']
      f_name = request.POST['first_name']
      l_name = request.POST['last_name']
      email = request.POST['email']
      password = request.POST['password']
      confirm_password = request.POST['confirm_password']
      try:
         """ create Client for tenant schema"""
         client =Client()
         client.domain_url = 'company1.user.com'
         client.schema_name = username
         client.name = company_name
         client.save()

         """ create user"""
         user = User()
         user.username = username
         user.first_name = f_name
         user.last_name = l_name
         user.email = email
         user.set_password(password)
         user.is_active = True
         user.is_staff = True
         user.save()

当用户登录从公共租户重定向到他们的私人客户租户帐户时,我想更改域 url。

我对这种功能很陌生。

任何人都可以给我一些指导或解决方案。

【问题讨论】:

  • 您能否在问题中添加更多详细信息/代码?

标签: django multi-tenant


【解决方案1】:

在创建用户之前,将您的数据库架构设置为新创建的架构。最好的方法是使用schema_context 上下文管理器。像这样的:

from tenant_schemas.utils import schema_context

with schema_context(client.schema_name):

    user = User()
    user.username = username
    user.first_name = f_name
    user.last_name = l_name
    user.email = email
    user.set_password(password)
    user.is_active = True
    user.is_staff = True
    user.save()

【讨论】:

  • 当我们进入schema_context 意味着我们现在在特定的数据库中。因此我们可以访问特定于租户的模型和 schema_context 中的所有公共模型。用户模型不是特定于租户的,它是一个公共模型。当您在schema_context 中创建用户对象时,它会再次保存到公共模型中。您可以通过在settings.py 中将django.contrib.auth 添加到您的TENANT_APPS 中来做到这一点。
【解决方案2】:

可能,在您的 settings.py 中,您的“django.contrib.auth”仅在您的 SHARED_APPS 中配置,这就是该用户仅出现在公共架构中的原因。 请检查您是否也在 TENANT_APPS 中声明了“django.contrib.auth”。

【讨论】:

    【解决方案3】:

    我建议你使用django-tenant-users。他们就是这么说的。

    此应用程序扩展了 django 用户和权限框架以与 django-tenant-schemas 或 django-tenants 一起工作,以允许全局用户在每个租户的基础上拥有权限。这允许单个用户属于多个租户和每个租户中的权限,包括允许公共租户中的权限。此应用还增加了对查询用户所属的所有租户的支持。

    因此您可以轻松管理django-tenant-schemasdjango-tenants 中的租户特定用户。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-22
      • 2015-07-08
      • 1970-01-01
      相关资源
      最近更新 更多