我对Django有点新鲜。我创建了一个自定义用户模型,因为我想使用该电子邮件进行身份验证,并按照文档中的示例运行良好并具有以下代码:
class CustomUserManager(BaseUserManager):
def _create_user(self, email, password,
is_staff, is_superuser, **extra_fields):
"""
Creates and saves a User with the given email and password.
"""
now = timezone.now()
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(email=email,
is_staff=is_staff, is_active=True,
is_superuser=is_superuser, last_login=now,
date_joined=now, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
return self._create_user(email, password, False, False,
**extra_fields)
def create_superuser(self, email, password, **extra_fields):
return self._create_user(email, password, True, True,
**extra_fields)
class User (AbstractBaseUser, PermissionsMixin):
'''
Custom User Model
'''
email = models.EmailField(verbose_name = "email address", max_length = 255, unique = True)
date_joined = models.DateTimeField('date joined', default=timezone.now)
first_name = models.CharField(_('first name'), max_length=30, blank=False)
last_name = models.CharField(_('last name'), max_length=30, blank=False)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
USERNAME_FIELD = "email"
REQUIRED_FIELDS = []
objects = CustomUserManager()
def get_absolute_url(self):
return "/users/%s/" % urlquote(self.email)
def get_full_name(self):
"""
Returns the first_name plus the last_name, with a space in between.
"""
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
"Returns the short name for the user."
return self.first_name
def email_user(self, subject, message, from_email=None):
"""
Sends an email to this User.
"""
send_mail(subject, message, from_email, [self.email])
我现在唯一的问题是我想在我的自定义用户模型中添加其他信息,例如可用性日期,个人资料图片,费用等(我正在制作一个mini linkedin网站)。我觉得在User模型中添加大量额外字段有点乱,随着时间的推移,字段数量会增加。有更好的方法吗?
由于
答案 0 :(得分:1)
正如您所描述的那样,没有理由不向此模型添加更多字段。这正是此自定义用户模型和模型迁移的用途。
如果您要为不同的用户创建不同的用户个人资料,可以使用multi table inheritance,如下所示:
class User (AbstractBaseUser, PermissionsMixin):
'''
Custom User Model
'''
...fields that are common to CreativeUser and ClientUser
class CreativeUser(User):
# Fields unique to CreativeUser
class ClientUser(User):
# Fields unique to ClientUser
现在,您可以使用User.objects.all()
查询所有用户,您可以查询CreativeUser.objects.all()
或ClientUser.objects.all()
。请注意,User.objects.all()
将不包含任何其他两个表中唯一的字段。
答案 1 :(得分:0)
至于你的要求,我建议你使用扩展名: django-custom-user