I am trying to implement a multi-tenant application in Django and PostgreSQL, with a separate (but identical) schema for every tenant.
I select the tenant schema with:
cursor.execute('SET search_path TO ' + schemas)
And I have a middleware that selects which schema to use based on the hostname, so it would work something like this:
foo.mysite.com --> use schema 'client_moo'
bar.mysite.com --> use schema 'client_bar'
This works in principle, that is in simple cases (simple db lookups)
However, things start to break down when I try to log in. Each tenant should have its own, separate log in page, so foo.mysite.com would be distinct from bar.mysite.com which would be distinct from mysite.com.
However, trying to login into the admin app from a subdomain results in a redirect back to the login page.
Here is what happens:
mysite.comlogs in fine (schema:public)foo.mysite.comninstead of logging in will redirect (HTTP 302) back to itself (foo.mysite.com) (schema:client_foo)
Forcing the schema to always be client_foo will result in mysite.com working (that is, logging in on the client_foo schema), but foo.mysite.com still not working.
Removing schema selection altogether (so that it is always on public schema) will make both URLs log in fine.
1) Did you set up your session cookie properly to support cross-domain sessions? See: https://docs.djangoproject.com/en/dev/topics/http/sessions/#session-cookie-domain
2) If you’re using DB session storage (which is the default), then switching schema will most likely result in Django not being able to fetch the session from the database (depends on order of your middleware).