用自定义字段扩展User模型(与Django的身份验证应用程序绑定)的最佳方法是什么?我还可能想使用电子邮件作为用户名(用于身份验证)。
我已经看到了一些方法,但不能决定哪一个是最好的。
用自定义字段扩展User模型(与Django的身份验证应用程序绑定)的最佳方法是什么?我还可能想使用电子邮件作为用户名(用于身份验证)。
我已经看到了一些方法,但不能决定哪一个是最好的。
当前回答
从Django 1.5开始,你可以很容易地扩展用户模型,在数据库中只保留一个表。
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"))
您还必须在设置文件中将其配置为当前用户类
# supposing you put it in apps/profiles/models.py
AUTH_USER_MODEL = "profiles.UserProfile"
如果你想添加很多用户的首选项,OneToOneField选项可能是一个更好的选择。
给开发第三方库的人一个提示:如果您需要访问用户类,请记住人们可以更改它。使用官方帮助获取正确的类
from django.contrib.auth import get_user_model
User = get_user_model()
其他回答
下面是另一种扩展User的方法。 我觉得它比上面两种方法更清晰,简单,易读。
http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/
使用上述方法:
你不需要使用 user.get_profile()。Newattribute访问额外的信息 与用户相关 你可以直接访问 通过 user.newattribute
注意:这个答案是不赞成的。如果你使用的是Django 1.7或更高版本,请参阅其他答案。
我就是这么做的。
#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'
这将在每次保存用户时创建一个用户配置文件。 然后你可以使用
user.get_profile().whatever
以下是文档中的更多信息
http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users
更新:请注意AUTH_PROFILE_MODULE自v1.5起已弃用:https://docs.djangoproject.com/en/1.5/ref/settings/#auth-profile-module
试试这个:
创建一个名为Profile的模型,并使用OneToOneField引用用户,并提供一个related_name选项。
models.py
from django.db import models
from django.contrib.auth.models import *
from django.dispatch import receiver
from django.db.models.signals import post_save
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_profile')
def __str__(self):
return self.user.username
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
try:
if created:
Profile.objects.create(user=instance).save()
except Exception as err:
print('Error creating user profile!')
现在要使用User对象直接访问配置文件,可以使用related_name。
views.py
from django.http import HttpResponse
def home(request):
profile = f'profile of {request.user.user_profile}'
return HttpResponse(profile)
在Django 3.0+版本中非常简单(如果你不是在项目中):
在models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
extra_field=models.CharField(max_length=40)
在settings.py
首先,注册你的新应用,然后在AUTH_PASSWORD_VALIDATORS下面 添加
AUTH_USER_MODEL ='users.CustomUser'
最后,在管理中注册你的模型,运行makemigrations和migrate,它将成功完成。
官方文档:https://docs.djangoproject.com/en/3.2/topics/auth/customizing/#substituting-a-custom-user-model
从Django 1.5开始,你可以很容易地扩展用户模型,在数据库中只保留一个表。
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"))
您还必须在设置文件中将其配置为当前用户类
# supposing you put it in apps/profiles/models.py
AUTH_USER_MODEL = "profiles.UserProfile"
如果你想添加很多用户的首选项,OneToOneField选项可能是一个更好的选择。
给开发第三方库的人一个提示:如果您需要访问用户类,请记住人们可以更改它。使用官方帮助获取正确的类
from django.contrib.auth import get_user_model
User = get_user_model()