A better way to import AUTH_USER_MODEL in Django 1.5

前端 未结 2 1740
隐瞒了意图╮
隐瞒了意图╮ 2021-01-13 11:41

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:

相关标签:
2条回答
  • 2021-01-13 12:02

    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()
    
    0 讨论(0)
  • 2021-01-13 12:14

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

    0 讨论(0)
提交回复
热议问题