0

I need to import a custom User model into a third party app, problem is this app import django's default User model, so:

from django.contrib.auth.models import User

I have a custom User, I could do this:

from myapp.models import User

but I want a generic solution.

I had tried:

1:

from django.contrib.auth import get_user_model
User = get_user_model()

output:

django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.

2:

from django.conf import settings
from django.db.models import get_model

app_label, model_name = settings.AUTH_USER_MODEL.split('.')
User = get_model(app_label, model_name)

output:

django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.

3:

from django.conf import settings
User = settings.AUTH_USER_MODEL

output:

TypeError

isinstance() arg 2 must be a class, type, or tuple of classes and types

specifically need execute this code

if isinstance(author, User) and author.is_authenticated():
    kwargs['author'] = u"%s <%s>" % (author.get_full_name() or author.username, author.email)
elif isinstance(author, six.string_types):
    kwargs['author'] = author

How I could do it? Thanks

aslheyrr
  • 372
  • 1
  • 4
  • 15

1 Answers1

0

I think that your "approach 1" is the right one, but the problem is that you can't run get_user_model() until after everything has been loaded. For example, you could change the main code to:

if isinstance(author, get_user_model()) and author.is_authenticated():
    kwargs['author'] = u"%s <%s>" % (author.get_full_name() or author.username, author.email)
elif isinstance(author, six.string_types):
    kwargs['author'] = author

That would be slow, since it runs get_user_model() each time, so you should find a place to keep the user model so that you only run get_user_model() the first time the code is called. For example, if this code is in a method of an object, you could put self._user_model = get_user_model() in the constructor.

Another option would be to check if the author is a string_types first, and then

try:
    kwargs['author'] = u"%s <%s>" % (author.get_full_name() or author.username, author.email)
except TypeError:
    # do whatever you already do, if the client code passes the wrong kind of object.
    pass
rescdsk
  • 8,739
  • 4
  • 36
  • 32