Home > Blockchain >  Select first image of image foreign key in django template
Select first image of image foreign key in django template

Time:12-22

I want to select first image of an object property set. I created a Property Model with a Foreign Key to an PropertyImages model. How do I access the first image of the property object_set.all in the template. I don;t want to do it in the view function since this should be in the base.html file.

the code:

{% for property in properties %}
        
        <div
          style="background-image: url('{{property.propertyimages_set.all|first.url}}'); background-size: 100% 100%; "
          ;
          
        >
          <div >
            <p><span>Name: </span>{{property.property_name}}</p>
            <hr>
            <p><span>Type: </span>{{property.property_type}}</p>
            <p><span>Price: </span>&#8358;{{property.price}}</p>
            <p><span>Location: </span>{{property.property_state}}</p>
            <p><a href="{% url 'property_details' property.property_slug %}">More info 
            >>></a></p>
          </div>
        </div>
        {% endfor %}

CodePudding user response:

You can use forloop.first to check if the loop is executed first and then use an appropriate if tag to display the image. Please see the for loop related variables from the link below:

Ref: https://docs.djangoproject.com/en/4.0/ref/templates/builtins/#for

{% if forloop.first %}
 # Show first image here

{% endif %}

CodePudding user response:

Try this:

Ref

<div style="background-image: url('{{properties.0.propertyimages_set.url}}'); background-size: 100% 100%;"; >
    <div >
        <p><span>Name: </span>{{properties.0.property_name}}</p>
        <hr>
        <p><span>Type: </span>{{properties.0.property_type}}</p>
        <p><span>Price: </span>&#8358;{{properties.0.price}}</p>
        <p><span>Location: </span>{{properties.0.property_state}}</p>
        <p><a href="{% url 'property_details' properties.0.property_slug %}">More info >>></a></p>
    </div>
</div>
  • Related