我有一个具有用户角色的Django模型。我希望当另一个用户角色或相同的用户角色登录时,能够在模板之外显示用户角色的First_Name、Last_Name和其他详细信息。
这是我的模特
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}}
1条答案
按热度按时间xoefb8l81#
如果您正在测试当前用户是否为房东,则可以在模板中执行所有这些操作,因为您始终可以参考Request.User User示例来查看谁在访问该页面。
然而,在您看来,您有一个问题。您正在使用GET(返回一条记录)来获取IS_LANDLOWER=True(这将是多个)的所有用户。这将给您一个错误。此外,您可能会对模板中引用的是哪个用户感到困惑,因为默认情况下,您的模板中已经有一个RQUE用户。试试这样的东西
现在,您可以在模板中执行以下操作
模板