How to use 'User' as foreign key in Django 1.5

前端 未结 2 840
我在风中等你
我在风中等你 2020-12-13 04:06

I have made a custom profile model which looks like this:

from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.         


        
相关标签:
2条回答
  • 2020-12-13 04:15

    Exactly in Django 1.5 the AUTH_USER_MODEL setting was introduced, allowing using a custom user model with auth system.

    If you're writing an app that's intended to work with projects on Django 1.5 through 1.10 and later, this is the proper way to reference user model (which can now be different from django.contrib.auth.models.User):

    class UserProfile(models.Model):
        user = models.ForeignKey(settings.AUTH_USER_MODEL)
    
    • See docs for more details.

    In case you're writing a reusable app supporting Django 1.4 as well, then you should probably determine what reference to use by checking Django version, perhaps like this:

    import django
    from django.conf import settings
    from django.db import models
    
    
    def get_user_model_fk_ref():
        if django.VERSION[:2] >= (1, 5):
            return settings.AUTH_USER_MODEL
        else:
            return 'auth.User'
    
    
    class UserProfile(models.Model):
        user = models.ForeignKey(get_user_model_fk_ref())
    
    0 讨论(0)
  • 2020-12-13 04:28

    Change this:

    user = models.ForeignKey('User', unique=True)
    

    to this:

    user = models.ForeignKey(User, unique=True)
    
    0 讨论(0)
提交回复
热议问题