Reputation: 1297
I'd like to switch databases upon user login. I've created this login signal.. but it doesn't work
from django.dispatch import receiver
from django.contrib.auth.signals import user_logged_in
from django.db import connections
@receiver(user_logged_in)
def db_switch(sender, **kwargs):
user_db = 'userdb_%s' % kwargs['user'].username
cursor = connections[user_db].cursor()
The databases are defined in settings.py
. Do I have to make this cursor global? Or is this all the way wrong way of doing it?
Thanks!
Upvotes: 2
Views: 2124
Reputation: 21032
It's the wrong way of doing it.
Honestly I don't think there is a straightforward, stable way of doing this in Django. It's just not designed for it.
Instead, I'd set up a settings_username
.py file for each user, which specifies a secondary database called personal or something. Then, after logging, have them redirect to a new domain, like username
.example.com, which uses a unique .wsgi file that pulls in the settingsusername
.py file.
Now, as far as the system is concerned, each website is totally separate and unique to that user. Just make sure to set the session cookie to example.com so that they're still logged in when they go to their user website.
Upvotes: 2