Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 14126

How to register a Django model for a specific database only

$
0
0

I am building a DJango multi-tenant web app that separates the tenants by giving them each their database. The app identifies the source and destination of the requests by checking the hostname. The localhost is the default tenant(me) using the default database and the subdomains from that are the tenants using their databases.

There is a model Tenants that I am using to create tenants and store their data. I want it to be only registered in the default database so that only I can SEE and edit it from the localhost admin but the tenant's admin can't.

I tried this and the only output was:

------------------------------TenantAdmin------------------------------

admin.py

from django.contrib import adminfrom .models import Tenantfrom .utils import hostname_from_the_request# Register your models here.class TenantAdmin(admin.ModelAdmin):    print("------------------------------TenantAdmin------------------------------")    def get_form(self, request, obj=None, **kwargs):        # Get the hostname from the request        current_hostname = hostname_from_the_request(request)        print("------------------------------Current hostname B4------------------------------", current_hostname)        # Check if the hostname is 'localhost'        if current_hostname == 'localhost':            return super().get_form(request, obj, **kwargs)        else:            print("------------------------------Current hostname------------------------------", current_hostname)            return None  # Returning None effectively hides the model in the admin# Register the Tenant model with the custom admin classadmin.site.register(Tenant, TenantAdmin)

So I also tried interfering with the migrations in the routers:routers.py

class TenantRouter:    def db_for_read(self, model, **hints):        return get_current_db_name()    def db_for_write(self, model, **hints):        return get_current_db_name()    def allow_relation(self, *args, **kwargs):        return True    def allow_syncdb(self, *args, **kwargs):        return None    def allow_migrate(self, db, app_label, model_name=None, **hints):        print(f"----------------Checking migration for app: {app_label}, model: {model_name}, database: {db}------")        if db == 'default' and model_name == 'Tenant':            print(f"Allowing migration only for database: DEFAULT")            return db == 'default'        return None

That did not work either. I can still see the Tenant model in the admins of the tenants. Any ideas?


Viewing all articles
Browse latest Browse all 14126

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>