How to suspend/deactivate a tenant?

Asked this question in django-tenants community, but no response there. Actually that community seems not quite active. See if anyone here have similar experience and can help me.
On django-tenants class TenantBase, there are delete() and delete_tenant() methods defined. The former is for completely delete a tenant, and the later will clear all users with their permissions from the tenant. I want to suspend/deactivate a tenant, so the tenant URL/schema will not be accessible by anyone other than system admin. Although the delete_tenant() can achieve this, but it removes all users and their from tenant, and so if activate it again, it cannot be operated as before.
What’s the correct way to modify a tenant, so it become completely not function, but still can be easily restored completely at later time?

Hey there!
I have not yet worked with django-tenants, but looking up into the source code of the models/middleware i figured it out a possible solution for your case. I suggest that you do this as well, looking up into the source code of some plugin may help you to become a better developer, you’ll learn how other people solves some of the problems you’re facing.
But hands on to the solution.

First, you defined your TenantModel, the one who inherits from the TenantMixin class. Can you share it here?
You’ll need to add a BooleanField to distinguish if this Tenant is active or not, is_active for example.
After you have this field you can activate/deactivate a tenant from the Admin or with a custom view, you probably already know how to do it.

After that, you have 2 options to only allow people to access active tenants:

  • Create a custom middleware that will do some filtering on the is_active attribute.
  • Create a custom manager on your Tenant model that does this filtering. You can check how to create a custom manager here.

I think that the first one may be better.
I’ll guide you through the solution:
You have added a django-tenants middleware to your MIDDLEWARES setting, according to the documentation it’s: django_tenants.middleware.main.TenantMainMiddleware
Now you’ll need to create a custom middleware, that inherits from this class (django_tenants.middleware.main.TenantMainMiddleware). And override the get_tenant method to filter the tenants with the is_active attribute. This method will be used here, so you can see that if there’s no tenant, the request will not go forward.
After you created the custom middleware, replace the django_tenants.middleware.main.TenantMainMiddleware with your custom middleware on the MIDDLEWARES setting.

Hope this helps, happy coding.

1 Like

Hi Leandro, I followed your suggestion and it exactly what I need.
Initially I was thinking to modify the domain URL in domain table, make it not usable. But feel your suggested solution is much better.
Thanks!

1 Like