我正在创建一个使用自定义用户模型的应用程序(使用 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
就是您所需要的。它是登录的 MyUser
的实例,它已经被 auth 中间件加载:
u = request.user
关于python - 使用Django登录后获取用户信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28023705/