Finding the profile name for a join in my Facebook auth backend I've written a project for handling various Facebook things and I ran into the issue where one project named the users profile Profile while normally they would be named UserProfile.  When I was checking if the FacebookUser model was related to a User, I could just User.objects.get(userprofile__facebook=facebook_user) so I come up with a way to get the name, but it seems pretty ugly. Is there a cleaner way?

from django.conf import settings
from django.contrib.auth.models import User
from better_facebook.models import FacebookUser

# Get the name of the AUTH profile so that we can check if the user
# has a relationship with facebook. Is there a neater way of doing this?
_lowercase_profile_name = settings.AUTH_PROFILE_MODULE.split(".")[1].lower()
_facebook_relation = '{0}__facebook'.format(_lowercase_profile_name)

class FacebookBackend(object):
    """
    Authenticate against a facebook_user object.
    """
    def authenticate(self, facebook_user):
        assert(isinstance(facebook_user, FacebookUser))
        try:
            return User.objects.get(**{_facebook_relation: facebook_user})
        except User.DoesNotExist:
            return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None
You can use django.contrib.auth.get_user_model() instead of importing User directly. Note that I also explicitly included the ObjectDoesNotExist exception.

https://docs.djangoproject.com/en/2.2/topics/auth/customizing/

from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ObjectDoesNotExist
from better_facebook.models import FacebookUser


class FacebookBackend(object):
    """
    Authenticate against a facebook_user object.
    """
    def authenticate(self, facebook_user):
        assert(isinstance(facebook_user, FacebookUser))
        try:
            UserModel = get_user_model()
            return UserModel.objects.get(userprofile__facebook=facebook_user)
        except ObjectDoesNotExist:
            return None

    def get_user(self, user_id):
        try:
            UserModel = get_user_model()
            return UserModel.objects.get(pk=user_id)
        except ObjectDoesNotExist:
            return None
```