How to get logged in user in django from custom users model

I want to get username from custom users model

My Custom Users model:

class Account(AbstractBaseUser, PermissionsMixin):
    nickname = models.CharField(max_length=150, unique=True)
    name = models.CharField(max_length=150)
    last_name = models.CharField(max_length=150)
    phone = models.CharField(max_length=50, unique=True)
    date_of_birth = models.DateField(blank=True, null=True)
    picture = models.ImageField(blank=True, null=True)
    is_staff = models.BooleanField(default=True)
    is_active = models.BooleanField(default=True)
    date_joined = models.DateTimeField(default=timezone.now)
    last_login = models.DateTimeField(null=True)
    admin_of_company = models.ForeignKey('companies.company', on_delete=models.CASCADE, default=None, blank=True,
                                         null=True)

    objects = AccountManager()

    USERNAME_FIELD = 'nickname'
    REQUIRED_FIELDS = ['name', 'last_name', 'phone']

    def get_full_name(self):
        return self.name, self.last_name

    def get_short_name(self):
        return self.name.split()[0]

and products model:

class products(models.Model):
    name = models.CharField(max_length=150)
    about = models.TextField()
    price = models.IntegerField()
    picture = models.ImageField(default=None)
    admin = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True)

in products.admin I want to set default logged in user but I don't know how to get this data from custom users model

If you would like to get a current account in your view use this

current_user_id = self.request.user.id
current_account = Account.objects.get(pk=current_user_id)
current_account_nickname = current_account.nickname

Your model Account doesn't have "username" field.

You have to add it if you would like to use "username".

class Account(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(max_length=150, unique=True)
Back to Top