Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A better way to import AUTH_USER_MODEL in Django 1.5

Tags:

python

django

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?

like image 210
boatcoder Avatar asked May 23 '13 20:05

boatcoder


2 Answers

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()
like image 146
karthikr Avatar answered Oct 04 '22 20:10

karthikr


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...

like image 39
Sergey Orshanskiy Avatar answered Oct 04 '22 21:10

Sergey Orshanskiy