Extending the User model with custom fields in Django

后端 未结 13 1424
别那么骄傲
别那么骄傲 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-21 23:59

    Since Django 1.5 you may easily extend the user model and keep a single table on the database.

    from django.contrib.auth.models import AbstractUser
    from django.db import models
    from django.utils.translation import ugettext_lazy as _
    
    class UserProfile(AbstractUser):
        age = models.PositiveIntegerField(_("age"))
    

    You must also configure it as current user class in your settings file

    # supposing you put it in apps/profiles/models.py
    AUTH_USER_MODEL = "profiles.UserProfile"
    

    If you want to add a lot of users' preferences the OneToOneField option may be a better choice thought.

    A note for people developing third party libraries: if you need to access the user class remember that people can change it. Use the official helper to get the right class

    from django.contrib.auth import get_user_model
    
    User = get_user_model()
    

提交回复
热议问题