I have created an API to register a shop. And after registering a shop, I tried to create an another Model object using post save signal. I am using "transaction.atomic()" as I have to create multiple model objects. While creating an object from signal I am getting
django.db.utils.InternalError: current transaction is aborted, commands ignored until end of transaction block
error.
Here is my code:
def post(self, request, *args, **kwargs):
"""This method uses atomic transaction, if an event gets
any error, whole transaction will be reversed."""
try:
with transaction.atomic():
data = request.data
name = data.get("name")
serializer = self.get_serializer(data=data)
serializer.is_valid(raise_exception=True)
new_schema_name = ShopCreateView.get_schema_name(data['name'])
serializer.save(schema_name=new_schema_name)
tenant = Client.objects.get(id=serializer.data['id'])
self.create_domain(tenant, new_schema_name)
username = f"{name}_admin"
email = data.get("business_email")
password = "password"
# Create the superuser object for the tenant
print(email)
self.create_superuser_for_tenant(tenant, username, email, password)
except Exception as exc:
return Response({"msg":str(exc)},status = status.HTTP_400_BAD_REQUEST)
return Response(serializer.data, status=status.HTTP_201_CREATED)
This is my views that is used to create a shop. Here I have used transaction.atomic() to manage the database consistency in case of error. And,
@receiver(post_schema_sync, sender=TenantMixin)
def create_shop_settings(sender, tenant, **kwargs):
with schema_context(tenant.schema_name):
ShopPreferenceModel.objects.create()
is my signal that is triggered when new tenant is migrated. Can anybody help me, why this error occurs.