我正在创建一个使用自定义用户模型的应用(使用AbstractBaseUser
方法)。我已经设法编写了所有相关的用户创建表单,并为用户提供了登录的方式。但是,当我尝试创建一个需要当前登录用户信息的页面时(例如编辑帐户页面)我是遇到麻烦。
我尝试了各种不同的方法,比如request.user
,但似乎没有一种方法能够很好地工作。当我尝试使用此方法时,我得到TypeError - “'MyUser'对象不支持索引”。
我附上我的模型类作为参考。
非常感谢任何帮助,提前谢谢。
models.py
class MyUserManager(BaseUserManager):
def create_user(self, email, date_of_birth, password=None):
"""
Creates and saves a User with the given email, date of
birth and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=MyUserManager.normalize_email(email),
date_of_birth=date_of_birth,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, date_of_birth, password):
"""
Creates and saves a superuser with the given email, date of
birth and password.
"""
u = self.create_user(email=email,
password=password,
date_of_birth=date_of_birth
)
u.is_admin = True
u.save(using=self._db)
return u
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
date_of_birth = models.DateField()
course = models.ForeignKey(Course, null=True)
location = models.ForeignKey(Location, null=True)
interests = models.ManyToManyField(Interest, null=True)
bio = models.TextField(blank=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['date_of_birth']
答案 0 :(得分:5)
您不应该从数据库加载用户。你只需要request.user
。它是已由auth中间件加载的已记录MyUser
的实例:
u = request.user