Reputation: 261
I figured out how to get the User created in a secondary database but I can't figure out what I should use in order to get the database to use the secondary database instead of the default database when looking if a User exists and then can be authenticated.
Say I have:
user = authenticate(username=username, password=password)
how do i tell django to use a database named secondary instead of using the default database?
Also, I assume that these follow along the same methods but how would i use login() or logout() by using the secondary database as well.
Upvotes: 0
Views: 438
Reputation: 11464
authenticate only takes credentials and is a shortcut to calling authenticate on your backends until you get a user:
https://github.com/django/django/blob/master/django/contrib/auth/init.py#L39
Assuming you are using the default backend ( https://github.com/django/django/blob/master/django/contrib/auth/backends.py#L4 ), there is no way to use this backend and select the non-default database, I think.
from django.contrib.auth.backends import ModelBackend
class NonDefaultModelBackend(ModelBackend):
"""
Authenticates against django.contrib.auth.models.User.
Using SOMEOTHER db rather than the default
"""
supports_inactive_user = True
def authenticate(self, username=None, password=None):
try:
user = User.objects.using("SOMEOTHER").get(username=username)
if user.check_password(password):
return user
except User.DoesNotExist:
return None
def get_user(self, user_id):
try:
return User.objects.using("SOMEOTHER").get(pk=user_id)
except User.DoesNotExist:
return None
I think this will give you the same behavior as the default backend but with the non-default db. Then you can add your backend to the settings or replace the default backend outright.
AUTHENTICATION_BACKENDS = (
'path.to.mybackends.NonDefaultModelBackend',
'django.contrib.auth.backends.ModelBackend',)
or so.
Upvotes: 1