Отображение данных роли User в Django Template
У меня есть модель django с ролями пользователей. Я хочу иметь возможность получить имя_пользователя, фамилию_пользователя и другие детали роли пользователя, отображаемые в другом шаблоне, когда другая роль пользователя или та же самая роль пользователя входит в систему.
Это мои модели
class User(AbstractUser):
is_customer = models.BooleanField(default=False)
is_employee = models.BooleanField(default=False)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
#username = models.CharField(unique = False , max_length=100)
#email = models.CharField(unique = True , max_length=100 )
nin = models.IntegerField(unique = False , null=True)
avatar = models.ImageField(null= True, default="avatar.svg")
is_landlord = models.BooleanField(default=False)
objects = UserManager()
REQUIRED_FIELDS= []
class Landlord(models.Model):
user = models.OneToOneField(User,related_name="prop_owner", null= True, on_delete=models.CASCADE)
bio = models.TextField(null=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS= []
objects = UserManager()
def __str__(self):
return str(self.user)
Это мои взгляды
def propertySingle(
request,
pk,
is_landlord,
):
user = User.objects.get(is_landlord=is_landlord)
property = Property.objects.get(id=pk)
properties = Property.objects.all()
images = Image.objects.filter(property=property)
context = {
"property": property,
"properties": properties,
"images": images,
'user':user,
}
return render(request, "base/page-listing-single.html", context)
Template
<div class="sl_creator">
<h4 class="mb25">Property Owned By:</h4>
<div class="media">
<img class="mr-3" style="width: 90px; height:90px;" src="{{request.user.avatar.url}}" alt="avatar">
<div class="media-body">
<h5 class="mt-0 mb0">{{user.last_name}} {{request.user.first_name}}</h5>
<a class="text-thm" href="#">View other Listings by {{property.landlord.last_name}} {{property.user.is_landlord.first_name}}
Вы можете сделать все это в шаблоне, если вы проверяете, является ли текущий пользователь арендодателем, потому что вы всегда можете обратиться к экземпляру request.user User, чтобы узнать, кто обращается к странице.
<h4 class="mb25">Property Owned By:</h4>
{% if request.user.is_landlord %}
...#show landlord details
{% else %}
This information only available to landlords
Однако в вашем представлении есть проблема. Вы используете get (возвращает одну запись), чтобы получить всех пользователей, у которых is_landlord = True (которых будет много). Это приведет к ошибке. Кроме того, вы можете запутаться, на какого пользователя вы ссылаетесь в своем шаблоне, поскольку по умолчанию в вашем шаблоне уже есть пользователь rquest. Попробуйте сделать что-то вроде этого
def propertySingle(
request,
pk,
):
# get the property and all info about the landlord
#now in the template we can access property.landlord with no extra db calls
property = Property.objects.get(id=pk).select_related('landlord')
properties = Property.objects.all()
images = Image.objects.filter(property=property)
context = {
"property": property,
"properties": properties,
"images": images,
}
return render(request, "base/page-listing-single.html", context)
Теперь в своем шаблоне вы можете сделать следующее
Шаблон
<div class="sl_creator">
<h4 class="mb25">Property Owned By:</h4>
{% if request.user == property.landlord %}
<!-- the user is THE landlord for this property -->
You: {{request. user.last_name}}, {{request.user.first_name}}
{% endif %}
{% if request.user.is_landlord %}
<!-- the user is A landlord, but not necessarily for this property -->
<div class="media">
<img class="mr-3" style="width: 90px; height:90px;" src="{{property.landlord.avatar.url}}" alt="avatar">
<div class="media-body">
<a class="text-thm" href="#">View other Listings by {{property.landlord.last_name}} {{property.landlord.first_name}}
</div>
</div>
{% else %}
<div class="media-body">
This information only available to landlords
</div>
{%end if %}