Davy
Davy

Reputation: 1796

Multi tenant django application using URL mappings instead of domain mappings

In django, most multi-tenant implementations (modules) are mapping hosts onto views.

e.g. mapping host/URL -> django view using postgress schema's:

customer1.myapp.com/view1/arg1 -> myapp.view1(arg1)  using schema 'customer1'
customer2.myapp.com/view1/arg1 -> myapp.view1(arg1)  using schema 'customer2'
customer3.myapp.com/view1/arg1 -> myapp.view1(arg1)  using schema 'customer3'

Since my PaaS (Pythonanywhere) is not supporting wildcard domains (*.myapp.com), I am trying to set up a multi-tenant application using URL mapping:

e.g. mapping URL -> django view:

myapp.com/customer1/view1/arg1 ->  myapp.view1(arg1) passing implicit parameter tenant='customer1'
myapp.com/customer2/view1/arg1 ->  myapp.view1(arg1) passing implicit parameter tenant='customer2'
myapp.com/customer3/view1/arg1 ->  myapp.view1(arg1) passing implicit parameter tenant='customer3'

Here some middleware should take care of passing the tenant parameter to the view and filtering query results for objects applicable to the selected tenant. e.g. https://django-tenant-schemas.readthedocs.io/en/latest/

But question here is: How to do this -which package can handle this- for URL mapping instead of host mapping?

Note: django-multitenants mentions "Supports url patterns as well as sub-domains" but not clear how to do this... https://pypi.python.org/pypi/django-multitenants

Upvotes: 2

Views: 1973

Answers (2)

Davy
Davy

Reputation: 1796

Solved with great help from Pythonanywhere support in following way:

  1. Create a new webapp for each tenant (yes, this is costing 2$ / month)
  2. Map the new domain to the new webapp (check pythonanywhere web tab "DNS setup")
  3. Have each webapp use the same code and the same postgres database (copy static & media patsh & wsgi script)
  4. Create the new schema in the postgres DB
  5. The rest is easy: follow the documentation of django-tenant-schemas

Roughly:

  • Sync the new schema: ./manage.py migrate_schemas --schema=my-new-tenant
  • Add the new tenant to the public tenant "customers_client" table
  • And if your user model is NOT in the public table: create new admin user for this tenant: ./manage.py createsuperuser --schema=my-new-tenant

Upvotes: 1

Giles Thomas
Giles Thomas

Reputation: 5867

From a bit of poking around in django-multitenants, it looks like it's meant to support URL-based multitenancy using a setting called TENANT_BASE_PATH

However... if you search the codebase of the project on GitHub, the only references to that setting appear in the documentation, not in the code itself. So it may be that django-multitenants isn't a finished project, but rather a work-in-progress that may have been abandoned (last commit was just 14 days after the initial commit).

Upvotes: 0

Related Questions