Home > OS >  Employee model details not showing in navbar in django template
Employee model details not showing in navbar in django template

Time:05-27

I have an issue showing my Employee name and picture in navbar.html

I have a CustomUser model from accounts app structure as below

core
  |_accounts
     |_models.py (CustomUser is in here)
  |
  |_employees
    |_models.py (Employee model in here)

My CustomUser is as below

class CustomUser(AbstractBaseUser, PermissionsMixin):
    email       = models.EmailField(_('email address'), unique=True)
    is_staff    = models.BooleanField(default=False)
    is_active   = models.BooleanField(default=True)
    date_joined = models.DateTimeField(default=timezone.now)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = CustomUserManager()

    def __str__(self):
        return self.email

and my employee model is

class Employee(models.Model):
    # PERSONAL DATA
    user        = models.ForeignKey(User,on_delete=models.CASCADE, related_name="employees")
    title       = models.CharField(_('Title'), max_length=10, default='Mr', choices=TITLE, blank=False, null=True)
    image       = models.ImageField(_('Profile Image'), upload_to='avatars/', blank=True, null=True, help_text='upload image < 2.0MB')#work on path username-date/image
    firstname   = models.CharField(_('Firstname'), max_length=125, null=False, blank=False)
    lastname    = models.CharField(_('Lastname'), max_length=125, null=False, blank=False)

In my navbar template I have

<img alt="image" src="{{ request.user.employees.image.url }}" >

and

<div >Hello {{ request.user.firstname }}</div>

My template is not showing the desired results

CodePudding user response:

First of all, your user field should be related to the CustomUser, not the User class. In addition, request.user will give you an instance of your AUTH_USER_MODEL setting in settings.py, which in your case is an instance of the CustomUser model, which instance does not have a firstname fields.

AbstractBaseUser does not come with a first_name, last_name fields, instead, you can switch your inheritance to an AbstractUser and then your CustomUser class would automatically inherit first_name and last_name.

Or as @Ankit suggested you can get the Employee first name by doing request.user.employee.firstname

Keep in mind, that your relationship should be OneToOne as @Iain suggested.

  • Related