python - 在django中自动为新Teanants创建新用户

标签 python django

我正在尝试使用 tenant-schema 开发 Multi-Tenancy Web 应用程序包。一切都工作正常,这里缺少一件事,即自动为新租户创建新用户。我知道我们可以使用此命令创建新的 super 用户

python manage.py tenant_command createsuperuser --schema=schema_name

但我想根据用户提供的信息自动创建新用户

这里我使用 api 创建租户,

api_view.py

    def post(self, request):
        serializer = ClientSerializer(data=request.data)
        if serializer.is_valid():
            try:
                serializer.save()
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            except Exception as e:
                return Response({'info': 'Unable to create tenant'})
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

租户模型

class Client(TenantMixin):
    name = models.CharField(max_length=100)
    paid_until = models.DateField()
    on_trial = models.BooleanField()
    created_on = models.DateField(auto_now_add=True)
    auto_create_schema = True

序列化器.py

from rest_framework import serializers

from .models import Client


class ClientSerializer(serializers.ModelSerializer):
    class Meta:
        model = Client
        fields = ['id', 'domain_url', 'schema_name', 'name', 'paid_until', 'on_trial', 'created_on']

在这里我想自动创建新的 super 用户。我不知道该怎么做,任何建议将不胜感激。

最佳答案

你可以使用 django post save signals .

例如在 models.py 中:

from django.dispatch import receiver
from tenant_schemas.utils import tenant_context
from django.contrib.auth.models import User

@receiver(post_save, sender=Client):
def create_superuser(instance, **kwargs):
  if 'created' in kwargs: # tests if this client was created
    tenant=instance
    with tenant_context(tenant):
    # Create the superuser by using the new client tenant schema
      User.objects.create_user(
        # insert your user data here
      )

关于python - 在django中自动为新Teanants创建新用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60389176/

相关文章:

python - Django - 在不重新启动开发服务器的情况下应用 HTML 和静态文件中的更改

python - 在 Alpine Linux 上的 python 上安装 snappy 时出现问题

python - Pandas:等效于 Excel sumifs

python - 检查字符串中是否仅存在指定的 Django 模板变量

python - 如何更改 Django REST Framework 中 RetrieveAPIView 中 lookup kwargs 字段的键?

python - 如何从代码而不是 Google App Engine 上的文件呈现 Django 模板

python - Django 迁移错误 KeyError : ('list' , u'user')

python - 让 Python 虚拟环境、Fabric 和 Sudo 协同工作

Python:改变音频文件的音高

Python - 有一个具有相同变量的子循环