Search code examples
pythondjangodjango-modelsdjango-admindjango-users

Getting user information after logging in with Django


I am creating an app that uses a custom user model (with the AbstractBaseUser method). I have managed to write all the relevant user creation forms and provided a way for the users to log in. However, when I try to create a page that requires information from the current logged in user (an edit account page for example) I am running into trouble. I have tried various different methods, like request.user, but none seem to work very well. When I try to use this method I get the TypeError - "'MyUser' object does not support indexing".

I am attaching my model classes for a reference.

Any help would be greatly appreciated, thanks in advance.

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']

Solution

  • You shouldn't load user from database. request.user is all you need. It is the instance of logged MyUser which is already loaded by auth middleware:

    u = request.user