For loop in Django template while changing the HTML each iteration - django

So I have this piece of HTML:
<div class="core-features-single">
<div class="row">
<div class="col-sm-6">
<div class="core-feature-img">
<img src="assets/images/watch-4.png" class="img-responsive" alt="Image">
</div>
</div>
<div class="col-sm-6">
<div class="core-feature-content arrow-left">
<i class="icofont icofont-brand-android-robot"></i>
<h4>Android and iOS Apps Install</h4>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat.</p>
</div>
</div>
</div>
</div>
<div class="core-features-single">
<div class="row">
<div class="col-sm-6">
<div class="core-feature-content arrow-right">
<i class="icofont icofont-ui-text-chat"></i>
<h4>Live Chat With Friends</h4>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat.</p>
</div>
</div>
<div class="col-sm-6">
<div class="core-feature-img">
<img src="assets/images/watch-5.png" class="img-responsive" alt="Image">
</div>
</div>
</div>
</div>
Which generates this kind output in the webpage:
But how do I iterate an HTML element like this? Because the text and image block order are changing each iteration.
What I came up with:
{% for entry in page.product_features_showcase.all %}
{% image entry.image height-1000 as img %}
<div class="core-features-single">
<div class="row">
<div class="col-sm-6">
<div class="core-feature-content arrow-{% cycle 'left' 'right' 'left' 'right' 'left' 'right' 'left' 'right' %}">
<i class="icofont icofont-phone"></i>
<h4>{{ page.product_features_showcase_title }}</h4>
<p>{{ page.product_features_showcase_description }}</p>
</div>
</div>
<div class="col-sm-6">
<div class="core-feature-img">
<img src="{{ img.url }}" class="img-responsive" alt="Image">
</div>
</div>
</div>
</div>
{% endfor %}
I know I can use cycle to make different CSS classes each iteration. But how to change the order of the HTML element? To make this HTML work in a loop.

Use forloop.counter and divisibleby inside a for loop to render different HTML blocks in odd and even loops:
{% if forloop.counter|divisibleby:2 %}
Right-arrow block
{% else %}
Left-arrow block
{% endif %}
In Django docs: https://docs.djangoproject.com/en/2.2/ref/templates/builtins/#divisibleby

Related

show related images to product in Django?

Hi I am trying to display all the images related to a particular product in a popup
My problem is the When I upload a photo for one of This Objects, it display on a both of Object how can i filter them for to display on the relavent object?
All Of This Objects on a same page
Photo 1
Popup
Admin Panel
my models.py
class Portfolio_Detail(models.Model):
title = models.CharField(max_length=50)
image = models.ImageField(upload_to='Portfolio/')
def __str__(self):
return self.title
class Portfolio_Image(models.Model):
portfolio = models.ForeignKey(Portfolio_Detail,on_delete=models.CASCADE,related_name="portfolio")
image = models.ImageField(upload_to='Portfolio_Image/')
my views.py
def home(request):
portfolios = Portfolio_Detail.objects.all()
portfolio_images = Portfolio_Image.objects.filter()
context = {
'portfolios' : portfolios,
'portfolio_images' : portfolio_images,
}
return render(request, "index.html", context)
My Template
<!-- Portfolio Section Start -->
<section class="portfolio-section sec-padding" id="portfolio">
<div class="container">
<div class="row">
<div class="section-title">
<h2>Recent Works</h2>
</div>
</div>
<div class="row">
<!-- Portfolio Item1 Start -->
{% for item in portfolios %}
<div class="portfolio-item">
<div class="portfolio-item-thumbnail">
<img src="{{item.image.url}}" alt="portfolio item Thumb">
</div>
<h3 class="portfolio-item-title">{{item.title}}</h3>
<button type="button" class="btn view-project-btn">View Project</button>
<div class="portfolio-item-details">
<div class="description">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
</div>
<div class="general-info">
<ul>
<li>Created : <span>4 dec 2020</span></li>
<li>Technology : <span>Html</span></li>
<li>Role : <span>Frontend</span></li>
<li>View Online : <span>www.domain.com</span></li>
</ul>
</div>
</div>
</div>
<!-- Portfolio Item1 End -->
{% endfor %}
</div>
</div>
</section>
<div class="portfolio-popup">
<div class="pp-inner">
<div class="pp-content">
<div class="pp-header">
<button type="button" class="btn pp-close"><i class="fas fa-times"></i></button>
<div class="pp-thumbnail">
{% for item in portfolio_images %}
<img src="{{item.image.url}}" alt="">
{% endfor %}
</div>
<h3></h3>
</div>
<div class="pp-body">
</div>
</div>
</div>
My Template code
<body>
<!-- Main Start -->
<div class="main hidden">
<!-- Portfolio Section Start -->
<section class="portfolio-section sec-padding" id="portfolio">
<div class="container">
<div class="row">
<div class="section-title">
<h2>Recent Works</h2>
</div>
</div>
<div class="row">
<!-- Portfolio Item1 Start -->
<div class="portfolio-item">
<div class="portfolio-item-thumbnail">
<img src="img/portfolio/1.jpg" alt="portfolio item Thumb">
</div>
<h3 class="portfolio-item-title">App Landing Page</h3>
<button type="button" class="btn view-project-btn">View Project</button>
<div class="portfolio-item-details">
<div class="description">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Qui natus numquam praesentium quidem dolorum explicabo molestiae reiciendis, iure suscipit placeat recusandae non nesciunt similique? Reprehenderit quia numquam eos quasi repudiandae.</p>
</div>
<div class="general-info">
<ul>
<li>Created : <span>4 dec 2020</span></li>
<li>Technology : <span>Html</span></li>
<li>Role : <span>Frontend</span></li>
<li>View Online : <span>www.domain.com</span></li>
</ul>
</div>
</div>
</div>
<!-- Portfolio Item1 End -->
</div>
</div>
</section>
</div>
<!-- Main End -->
<!-- Portfolio Item Detail Start -->
<div class="portfolio-popup">
<div class="pp-inner">
<div class="pp-content">
<div class="pp-header">
<button type="button" class="btn pp-close"><i class="fas fa-times"></i></button>
<div class="pp-thumbnail">
<img src="" alt="">
</div>
<h3></h3>
</div>
<div class="pp-body">
</div>
</div>
</div>
</div>
<!-- Portfolio Item Detail End -->
<script src="js/script.js"></script>
</body>
</html>
You can change your models.py like below:
class PortfolioImage(models.Model):
image = models.ImageField(upload_to='portfolio_image/')
class PortfolioDetail(models.Model):
title = models.CharField(max_length=50)
images = models.ManyToManyField(PortfolioImage)
def __str__(self):
return self.title
then in your HTML:
<!-- Portfolio Section Start -->
<section class="portfolio-section sec-padding" id="portfolio">
<div class="container">
<div class="row">
<div class="section-title">
<h2>Recent Works</h2>
</div>
</div>
<div class="row">
<!-- Portfolio Item1 Start -->
{% for item in portfolios %}
<div class="portfolio-item">
<div class="portfolio-item-thumbnail">
<img src="{{ item.image.url }}" alt="portfolio item Thumb">
</div>
<h3 class="portfolio-item-title">{{ item.title }}</h3>
<button type="button" class="btn view-project-btn">View Project</button>
<div class="portfolio-item-details">
<div class="description">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
</div>
<div class="general-info">
<ul>
<li>Created : <span>4 dec 2020</span></li>
<li>Technology : <span>Html</span></li>
<li>Role : <span>Frontend</span></li>
<li>View Online : <span>www.domain.com</span></li>
</ul>
</div>
</div>
</div>
<!-- Portfolio Item1 End -->
{% for portfolio_image in item.images.all %}
<div class="portfolio-popup">
<div class="pp-inner">
<div class="pp-content">
<div class="pp-header">
<button type="button" class="btn pp-close"><i class="fas fa-times"></i></button>
<div class="pp-thumbnail">
{% for item in portfolio_images %}
<img src="{{ item.image.url }}" alt="">
{% endfor %}
</div>
<h3></h3>
</div>
<div class="pp-body">
</div>
</div>
</div>
</div>
{% endfor %}
{% endfor %}
</div>
</div>
</section>

Django forloop change template after x element

Hi, I try to achieve a custom grid with bootstrap 4 using forloop counter. Unfortunately for me, something causes the elements to fall apart. I know I'm close to achieving this but I try to do this for several hours and still I failed to do this.
My code:
{% for article in healtharticles %}
<div class="col-lg-4 col-md-12 mb-4 mb-lg-0">
<!-- News block -->
{% if forloop.counter0 < 1 %}
<div>
<!-- Featured image -->
<div class="bg-image hover-overlay shadow-1-strong ripple rounded-5 mb-4" data-mdb-ripple-color="light">
<img src="https://mdbootstrap.com/img/new/fluid/city/113.jpg" class="img-fluid" />
<a href="#!">
<div class="mask" style="background-color: rgba(251, 251, 251, 0.15);"></div>
</a>
</div>
<!-- Article data -->
<div class="row mb-3">
<div class="col-6">
<a href="" class="text-info">
<i class="fas fa-plane"></i>
Travels
</a>
</div>
<div class="col-6 text-end">
<u> 15.07.2020</u>
</div>
</div>
<!-- Article title and description -->
<a href="" class="text-dark">
<h5>This is title of the news</h5>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Odit, iste aliquid. Sed
id nihil magni, sint vero provident esse numquam perferendis ducimus dicta
adipisci iusto nam temporibus modi animi laboriosam?
</p>
</a>
{% else %}
<hr />
<!-- News -->
<a href="" class="text-dark">
<div class="row mb-4 border-bottom pb-2">
<div class="col-3">
<img src="https://mdbootstrap.com/img/new/standard/city/041.jpg"
class="img-fluid shadow-1-strong rounded" alt="" />
</div>
<div class="col-9">
<p class="mb-2"><strong>Lorem ipsum dolor sit amet</strong></p>
<p>
<u> 15.07.2020</u>
</p>
</div>
</div>
</a>
</div>
{% endif %}
<!-- News block -->
</div>
{% endfor %}
Maybe someone has an idea of what's is wrong.
You have not closed div in if condition and opened div in else condition.
{% if forloop.counter0 < 1 %}
<div>
......
</a>
</div> <!-- Close div here-->
{% else %}
<div> <!-- Open div here -->
.....
</div>
{% endif %}

How to limit data in html using django template?

I am using bootstrap carousel and i am using for template to iterate through data but i want two data at once so i wanted to do was if data exceeds 2 i want to display nothing after that can some one tell me how to do it.
<section id="latest-trip">
<div class="container">
<div class="row col-md-12">
<!-- Latest trip left part(carousel part) Start -->
<div id="treaking-list" class="col-md-7 ml-4">
<div
id="carouselExampleIndicators-three"
class="carousel slide"
data-ride="carousel"
>
<ol class="carousel-indicators">
<li
data-target="#carouselExampleIndicators-three"
data-slide-to="0"
class="active"
></li>
<li
data-target="#carouselExampleIndicators-three"
data-slide-to="1"
></li>
<li
data-target="#carouselExampleIndicators-three"
data-slide-to="2"
></li>
</ol>
<div class="carousel-inner">
{% for tour in tours %}
<div class="carousel-item {% if tour.id == 1 %} active {% endif %}">
<div class="row">
{% for tour in tours %}
<div class="treaking col-md-6">
<img
src="{{tour.image}}"
alt="Real Adventure Nepal - {{tour.tour_name}}"
title="{{tour.tour_name}}"
/>
<div class="treaking-head">
<h3>{{tour.tour_name}}</h3>
<p>
{{tour.description}}
</p>
</div>
</div>
{% endfor %}
</div>
</div>
{% endfor %}
</div>
</div>
</div>
<!-- Latest trip left part(carousel part) End -->
<!-- Latest trip right part(Description part) Start -->
<div class="col-md-4 ml-5 title">
<h2 class="treaking-title">Latest Trips</h2>
<span class="right-styled-para">Explore the unexplored world</span>
<p class="treaking-description">
Lorem ipsum dolor sit amet consectetur adipiscing elitsed do eiusmod
tempor incididunt utlabore et dolore magna aliqua. Utenim ad minim
veniam quiso.
</p>
<button type="button" class="btn btn-primary join-us">
Join us now
</button>
</div>
<!-- Latest trip right part(Description part) End -->
</div>
</div>
</section>
What is Currently happening is that the data are going down and same thing keeps going on in carousel :
<section id="latest-trip">
<div class="container">
<div class="row col-md-12">
<!-- Latest trip left part(carousel part) Start -->
<div id="treaking-list" class="col-md-7 ml-4">
<div
id="carouselExampleIndicators-three"
class="carousel slide"
data-ride="carousel"
>
<ol class="carousel-indicators">
<li
data-target="#carouselExampleIndicators-three"
data-slide-to="0"
class="active"
></li>
<li
data-target="#carouselExampleIndicators-three"
data-slide-to="1"
></li>
<li
data-target="#carouselExampleIndicators-three"
data-slide-to="2"
></li>
</ol>
<div class="carousel-inner">
{% for tour in tours[:2] %}
<div class="carousel-item {% if tour.id == 1 %} active {% endif %}">
<div class="row">
{% for tour in tours %}
<div class="treaking col-md-6">
<img
src="{{tour.image}}"
alt="Real Adventure Nepal - {{tour.tour_name}}"
title="{{tour.tour_name}}"
/>
<div class="treaking-head">
<h3>{{tour.tour_name}}</h3>
<p>
{{tour.description}}
</p>
</div>
</div>
{% endfor %}
</div>
</div>
{% endfor %}
</div>
</div>
</div>
<!-- Latest trip left part(carousel part) End -->
<!-- Latest trip right part(Description part) Start -->
<div class="col-md-4 ml-5 title">
<h2 class="treaking-title">Latest Trips</h2>
<span class="right-styled-para">Explore the unexplored world</span>
<p class="treaking-description">
Lorem ipsum dolor sit amet consectetur adipiscing elitsed do eiusmod
tempor incididunt utlabore et dolore magna aliqua. Utenim ad minim
veniam quiso.
</p>
<button type="button" class="btn btn-primary join-us">
Join us now
</button>
</div>
<!-- Latest trip right part(Description part) End -->
</div>
</div>
</section>
Adding [:2] after tours will resolve it. See my above answer.

How to pass dictionary value as path to image in django?

I am a beginner in django and currently struggling to pass dict value as path to image. I have dictionary in following format:-
{
'features': [
{
'icon': 1,
'heading': 'Lorem Ipsum',
'description': 'Neque porro quisquam est qui ipsum quia dolor sit amet, adipiscing velit quia dolor sit
amet, adipisci velit'
},
{
'icon': 2,
'heading': 'Lorem Ipsum',
'description': 'Neque porro quisquam est qui ipsum quia dolor sit amet, adipiscing velit quia dolor sit
amet, adipisci velit'
}
]
}
Inside template, I am accessing images in following way:-
{% for feature in content.features %}
<div class="col-lg-4 col-md-6 col-sm-12 mx-auto my-1 mt-5 text-center d-flex flex-column align-items-center">
<div class="h-40 w-100 d-flex">
<img class="img-fluid mx-auto" src="{% static "base/images/{{feature.icon}}" %}"
alt="{{ feature.heading }}" width="100" height="100">
</div>
<div class="h-60 w-100 d-flex flex-column">
<h4 class="feature-caption">{{ feature.heading }}</h4>
<p class="feature-description p-2 pt-3 pb-3">{{ feature.description }}</p>
</div>
</div>
{% endfor %}
However, the images are not loading. Can someone suggest how to solve this?
In case you are using Djangos template syntax, I don't think you can use use {{ }} inside a template tag (that uses {% %}). So the following part is not valid:
src="{% static "base/images/{{feature.icon}}" %}"
You can try to use the add template filter instead.
This filter is not intended to be used for strings, only for numbers, but if both parts are strings then it works regardless. Like this:
{% with icon_as_str=feature.icon|stringformat:'d' %}
src="{% static 'base/images/'|add:icon_as_str %}"
{% endwith %}
Or just convert your icon to string in the view and forget about the {% with ... %} block.
Related answer: https://stackoverflow.com/a/4524851/9225671
Assuming that from your views you pass the dictionary as a variable named content , the way you are calling the values you want is correct:
{% for feature in content.features %}
{{ feature.icon }}
{{ feature.heading }}
{{ feature.description }}
{% endfor %}
Before that, make sure you have the {% load staticfiles %} declared as the very first line inside your html file.

Bootstrap carousel template not working in django

I am trying to add bootstrap carousel to my home page in django app it is not changing slide.
templates/posts/index.html
{% extends "posts/base.html" %}
{% block content %}
<div class="container pt-3 mh-50">
<div class="bd-example">
<div id="carouselExampleCaptions" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
{% for fpost in featured_post %}
{% if forloop.counter == 1 %}
<div class="carousel-item active">
{% else %}
<div class="carousel-item">
{% endif %}
<img src="{{fpost.thumbnail.url}}" class="d-block w-100" alt="...">
<div class="carousel-caption d-none d-md-block">
<h5>{{fpost.title}}</h5>
<p>Nulla vitae elit libero, a pharetra augue mollis interdum.</p>
</div>
</div>
{% endfor %}
</div>
<ol class="carousel-indicators">
<li data-target="#carouselExampleCaptions" data-slide-to="0" class="active"></li>
<li data-target="#carouselExampleCaptions" data-slide-to="1"></li>
<li data-target="#carouselExampleCaptions" data-slide-to="2"></li>
</ol>
</div>
</div>
</div>
views.py
def index(request):
featured = Post.objects.filter(featured = True) #put this on carousel
latest_post = Post.objects.order_by('-timestamp')[:6]
startup_post = Post.objects.filter(category__title__iexact='startup')[0:3]
opinion_post = Post.objects.filter(category__title__iexact='opinion')[0:3]
# add a video field here
context = {
'featured_post': featured,
'latest_post': latest_post,
'startup_post': startup_post,
'opinion_post': opinion_post
}
return render(request, 'posts/index.html', context)
I am trying to render post with featured post true on carousel. It is giving me just static picture without any slideshow.
Try this...Also don't forget to include bootstrap styles.
And also could you tell me why are you using block {% if ...%}? It is useless in you example.
{% extends "posts/base.html" %}
{% block content %}
<div class="container mt-5">
<div class="bd-example">
<div id="carouselExampleCaptions" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#carouselExampleCaptions" data-slide-to="0" class="active"></li>
<li data-target="#carouselExampleCaptions" data-slide-to="1"></li>
<li data-target="#carouselExampleCaptions" data-slide-to="2"></li>
</ol>
<div class="carousel-inner">
{% for fpost in featured_post %}
<div class="carousel-item active">
<img src="{{fpost.thumbnail.url}}" class="d-block img-responsive" height="650px !important" width="100%">
<div class="carousel-caption d-none d-md-block">
<h5>{{fpost.title}}</h5>
<p>Nulla vitae elit libero, a pharetra augue mollis interdum.</p>
</div>
{% endfor %}
</div>
<a class="carousel-control-prev" href="#carouselExampleCaptions" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleCaptions" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
</div>
{% endblock %}
Call the carousel over javascript (add this inside your html):
<script>
$('.carousel').carousel()
</script>