I have the Django User model and I created Employee model as below
class Employee(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='employees')
title = models.CharField(_('Title'), max_length=6, default='Mr', choices=TITLE, blank=False, null=True)
firstname = models.CharField(_('Firstname'), max_length=125, null=False, blank=False)
In my sidebar.html I can access the username as {{ request.user }}
but I want to show the title
and firstname
from the Employee model on the sidebar.html
CodePudding user response:
You are using ForeignKey
to link Employee to User, so from User instance you can access a QuerySet of all related Employee objects (using related_name you provided). Like that:
{% for employee in request.user.employees.all %}
{{ employee.title }} {{ employee.firstname }}
{% endfor %}
If you plan to have exactly one Employee object for one User object, it's better to use:
user = models.OneToOneField(User, on_delete=models.CASCADE)
because then you can easily get Employee
field values:
{{ request.user.employee.title }} {{ request.user.employee.firstname }}