Extending the User model with custom fields in Django

后端 未结 13 1432
别那么骄傲
别那么骄傲 2020-11-21 23:28

What\'s the best way to extend the User model (bundled with Django\'s authentication app) with custom fields? I would also possibly like to use the email as the username (fo

13条回答
  •  一生所求
    2020-11-22 00:22

    Note: this answer is deprecated. see other answers if you are using Django 1.7 or later.

    This is how I do it.

    #in models.py
    from django.contrib.auth.models import User
    from django.db.models.signals import post_save
    
    class UserProfile(models.Model):  
        user = models.OneToOneField(User)  
        #other fields here
    
        def __str__(self):  
              return "%s's profile" % self.user  
    
    def create_user_profile(sender, instance, created, **kwargs):  
        if created:  
           profile, created = UserProfile.objects.get_or_create(user=instance)  
    
    post_save.connect(create_user_profile, sender=User) 
    
    #in settings.py
    AUTH_PROFILE_MODULE = 'YOURAPP.UserProfile'
    

    This will create a userprofile each time a user is saved if it is created. You can then use

      user.get_profile().whatever
    

    Here is some more info from the docs

    http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users

    Update: Please note that AUTH_PROFILE_MODULE is deprecated since v1.5: https://docs.djangoproject.com/en/1.5/ref/settings/#auth-profile-module

提交回复
热议问题