boatcoder
boatcoder

Reputation: 18117

A better way to import AUTH_USER_MODEL in Django 1.5

I'm trying to make plugable apps more resilient under Django 1.5 where you now have a custom definable user model.

When adding foreign keys to a model I can do:

user = models.ForeignKey(settings.AUTH_USER_MODEL)

which saves me the import of User at the top of the file that breaks when django.contrib.auth.models.User is no longer the user model. But sometimes when testing, I need to be able to create a user, and the best I've been able to come up with for this is

from django.conf import settings
from django.db.models import get_model
User = get_model(*settings.AUTH_USER_MODEL.split('.'))

then I can do things like:

User.objects.create(username="test")

within my test (some objects have FK's tied to users and I need one of those objects in a test).

It doesn't strike me as particularly elegant, but I really don't see any cleaner way to do this in 1.5.

Did I miss something in the docs?

Upvotes: 5

Views: 3778

Answers (2)

Sergey Orshanskiy
Sergey Orshanskiy

Reputation: 7054

Just remember, get_user_model cannot be called at module level. In particular, do not even think of using it in models.py to define a ForeignKey relationship. Use the AUTH_USER_MODEL setting if you have to.

Otherwise, as I have discovered, you will be getting weird and difficult-to-debug bugs where certain models just won't be available. In fact, I had a situation where just adding print get_user_model() to a certain file caused another import to fail, in a totally different django app.

If I read this introduction to get_user_model, I could have saved myself a few hours...

Upvotes: 7

karthikr
karthikr

Reputation: 99670

One way you could do it is:

try:
    from django.contrib.auth import get_user_model
except ImportError: # django < 1.5
    from django.contrib.auth.models import User
else:
    User = get_user_model()

Upvotes: 11

Related Questions