Auto Create new User for new teanants in django

Viewed 1179

I'm trying to develop multi tenants web applications using tenant-schema packages. Every things is working fine, Here one thing is missing that is automatically create new user for new tenants. I know we can create new super user using this command

python manage.py tenant_command createsuperuser --schema=schema_name

But i want to automatically create new user on basis of information provided by the user

Here I'm creating tenants using 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)

Model for tenants

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

serializers.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']

Here i want to create new superuser automatically. I didn't know how to do, any suggestion would be appreciated.

2 Answers

So you need to create new user based on information provided by user on an HTML page. For this you will need to create an html page to get the information, with submit button. Once the submit button is clicked, below view can be used to create new user.

def createUser(request):
    if request.user.is_authenticated:
        if request.method == "POST":
            first_name = request.POST['first_name']
            last_name = request.POST['last_name']
            userName = request.POST['first_name']+request.POST['mobile_number']
            userMail = request.POST['email']
            if userName and userMail and last_name and first_name:
                   u, created = User.objects.get_or_create(email=userMail, 
                   first_name=first_name, last_name=last_name, defaults={'username': userName})
               if created:
                   print('user created')
                   return render(request, 'Success.html', {'message': 'User Created Successfully.'})
               else:
                   return render(request, 'index.html', {'message': 'User has not been created.'})
            else:
                return render(request, 'index.html', {'message': 'Please provide all the detail.'})

You could use django post save signals.

For example in 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
      )
Related