Display the data of User role in Django Template

Question:

I have a django model with User roles. I want to be able to get the first_name, last_name and other details of a user role displayed other a template when another user role or the same user role is logged in.

This is my models


    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)

This is my views


    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}}
Asked By: Sir Feranmi

||

Answers:

You can do all this in the template if all you are testing for if the current user is a landlord, because you can always refer to the request.user User instance to see who is accessing the page.

<h4 class="mb25">Property Owned By:</h4>
{% if request.user.is_landlord %}
     ...#show landlord details
{% else %}
    This information only available to landlords

However, you have a problem in your view. You are using get (returns one record) to get all the users who have is_landlord = True (which will be many). This will give you an error. Also, you may get confused about which user you are referring to in your template as there ius already a rquest user in your tempalte by default. Try something like this

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)

Now in your template you can do the following

Template

<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 %}
Answered By: SamSparx
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.