[嗨,我想向我的用户模型中添加一些额外的字段,并从abstractuser类继承读取自定义用户模型,但是当我实现用户模型时,Django用户名字段等消失了。一种解决方案是使用其他模型(例如个人资料),但我想向Django用户模型添加额外的字段。这可能吗?谢谢,请不要对这个问题给我投反对票
您可以使用自定义的用户模型:
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
"""
Custom User Model
"""
TIMEZONES = tuple(zip(pytz.all_timezones, pytz.all_timezones))
username = models.CharField(max_length=255, unique=True)
full_name = models.CharField(max_length=255, blank=True, null=True)
email = models.CharField(max_length=255, unique=True)
image = models.ImageField(upload_to=get_image_path, blank=True, null=True)
timezone = models.CharField(max_length=32, choices=TIMEZONES, default="UTC")
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["username"]
def __str__(self):
return self.email
您将必须在settings.py
文件中注册您的自定义模型:
# Registering the Custom User Model
AUTH_USER_MODEL = 'my_app.User'
最简单的方法是制作另一个模型,该模型将与django User模型具有OneToOne
关系。
例如,假设此模型Profile
将保存用户图像,地址,电话等。
class Profile(models.Model):
image = models.ImageField(upload_to='/image/')
address = models.CharField(max_length=255)
... # other fields
user = models.OneToOneField(User,on_delete=models.CASCADE) # this must be OneToOne
现在您可以使用此模型来创建用户的个人资料,如下所示:
首先在视图中保存Django默认用户模型
if form.is_valid():
user = form.save() # which will save your user model with fields like username,password,email
# Now after saving the user you can create profile of that user like this:
Profile.objects.create(user=user,image=form.cleaned_data['image'],....)
注意:这只是一个例子