我正在创建一个使用自定义用户模型的应用程序(使用AbstractBaseUser
方法)。我已经成功地编写了所有相关的用户创建表单,并为用户提供了登录的方法。但是,当我试图创建一个需要当前登录用户信息的页面(例如编辑帐户页面)时,我遇到了麻烦。
我尝试过各种不同的方法,比如request.user
,但似乎没有一种效果很好。当我尝试使用这个方法时,我得到了TypeError-“'MyUser'对象不支持索引”。你知道吗
我附上我的模型类作为参考。你知道吗
任何帮助都将不胜感激,提前谢谢。你知道吗
型号.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']
不应该从数据库加载用户。
request.user
就是你所需要的。它是已由auth中间件加载的loggedMyUser
的实例:相关问题 更多 >
编程相关推荐