How to use Django for loop twice on the same data - python

I'm attempting to use a for loop to iterate over the same data twice in the same Django template. However the second for loop only returns the first object in the database.
Basically I have an image of each job in the database on the homepage and when clicked on it should display a more detailed description of that job. All the jobs from the database display fine on the homepage but they all display the description of the first job when clicked on.
I think it's something to do with only being able to use an iterator once but I can't figure out what the solution is.
model.py
from django.db import models
class Job(models.Model):
title = models.CharField(max_length=50, default="Example Work")
image = models.ImageField(upload_to='images/')
summary = models.TextField()
views.py
from django.shortcuts import render
from .models import Job
def get_index(request):
jobs = Job.objects
return render(request, 'index.html', {'jobs': jobs})
index.html
{% for job in jobs.all %}
<div class="col-md-6 col-lg-4">
<a class="portfolio-item d-block mx-auto" href="#portfolio-modal">
<div class="portfolio-item-caption d-flex position-absolute h-100 w-100">
<div class="portfolio-item-caption-content my-auto w-100 text-center text-white">
<i class="fas fa-search-plus fa-3x"></i>
</div>
</div>
<img class="img-fluid" src="{{ job.image.url }}" alt="">
</a>
<h3 class="text-center text-secondary">{{ job.title }}</h3>
</div>
{% endfor %}
<!-- Portfolio Modal -->
{% for job in jobs.all %}
<div class="portfolio-modal mfp-hide" id="portfolio-modal">
<div class="portfolio-modal-dialog bg-white">
<a class="close-button d-none d-md-block portfolio-modal-dismiss" href="#">
<i class="fa fa-3x fa-times"></i>
</a>
<div class="container text-center">
<div class="row">
<div class="col-lg-8 mx-auto">
<h2 class="text-secondary text-uppercase mb-0">{{ job.title }}</h2>
<hr class="star-dark mb-5">
<img class="img-fluid mb-5" src="{{ job.image.url }}" alt="Image of website">
<p class="mb-5">{{ job.summary }}</p>
<a class="btn btn-primary btn-lg rounded-pill portfolio-modal-dismiss" href="#">
<i class="fa fa-close"></i>Close Project</a>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
Just for context, I've ripped out a lot of the html code from index.html because that all works fine and it probably isn't relevant. I've tried it in within one loop which doesn't work either. The description opens up within a new window on the same page. I've tried anything I can think of but not getting anywhere with it. Still getting to grips with Django and Python. Any help appreciated.

This isn't anything to do with Django outputting the same data for each iteration. If you check the generated HTML via View Source in your browser, you'll definitely see the correct data.
The problem is with your HTML itself. You cannot have multiple elements with the same HTML id attribute; but you are using id="portfolio-modal" for each one. When your JS tries to pop up the modal, it will only ever find the first instance of this ID.
You need to use a different ID in each iteration - perhaps by appending a unique element, eg the Job pk - and/or use a class to trigger your modal.

Related

How to insert images from render( , , context) in Django?

guys! New in Django so maybe it's a silly question. I have a .json file that keeps information about shop's clothes including "img". The goal is to otput all the information about products in a single "for loop". So I've written such lines
{% for product in products %}
<div class="col-lg-4 col-md-6 mb-4">
<div class="card h-100">
<a href="#">
<img class="card-img-top"
src="{% static '{{ product.img }}' %}" !!! problem is here
alt="">
</a>
<div class="card-body">
<h4 class="card-title">
{{ product.name }}
</h4>
<h5>{{ product.price }}</h5>
<p class="card-text"> {{ product.description }}</p>
</div>
<div class="card-footer text-center">
<button type="button" class="btn btn-outline-success">Отправить в корзину</button>
</div>
</div>
</div>
{% endfor %}
Everything works fine except the line concerns an image. In devtools I get the next path "/static/%7B%7B%20product.img%20%7D%7D". But in the .json file it looks like "img": "vendor/img/products/Brown-sports-oversized-top-ASOS-DESIGN.png". I am totally confused about that situation and definitely in a bind. I appreciate any help
work with:
<img src="{{ product.img.url }}">
if the image is effective (product.img is not None), and you added the media urls to the urls.py, then it will determine the URL where to fetch the product image.
Note that in production, Django does not serve media files, so in that case you will need to configure the webserver (Apache, Nginx, etc.) to serve media files for you.

Using For loop and If condition in Django to display Images in Bootstrap Carousel

I haven been looking everywhere for a case similar to this, but haven't found anything that could solve my problem. I want to display an image from a model in my html inside a for loop, which has an if condition. This is my models.py:
from django.db import models
# Create your models here.
class CarouselItem(models.Model):
carousel_picture = models.ImageField(upload_to='carousel_images/', null=True, blank=True)
views.py:
from django.shortcuts import render
from .models import CarouselItem
# Create your views here.
def index(request):
carousel_items = CarouselItem.objects.all()
context = {
'carousel_items': carousel_items
}
return render(request, "home/index.html", context=context)
and my html:
{% if carousel_items %}
<div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
{% for item in carousel_items %}
{% if forloop.first %}
<div class="carousel-item active">
<img src="{% item.carousel_picture.url %}" class="d-block w-100" alt="...">
</div>
{% else %}
<div class="carousel-item">
<img src="{% item.carousel_picture.url %}" class="d-block w-100" alt="...">
</div>
{% endif %}
{% endfor %}
<a class="carousel-control-prev" href="#carouselExampleControls" 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="#carouselExampleControls" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
{% else %}
<h3>We are sorry, there are currently no Images to display</h3>
{% endif %}
When I want to access the page associated with the html I get this error message:
Invalid block tag on line 86: 'item.carousel_picture.url', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag?
I feel like I am making a mistake somewhere else, but I can't figure out what it is. I am using Bootstrap 4.5.3 and Django 3.1.5
All of the other html files in this project have no issues with displaying images using for loops.
Instead of using:
{% item.carousel_picture.url %}
which is for templates logic, use:
{{ item.carousel_picture.url }}
which uses the value.

i have a issue in view job button in Django Project

I am new in Django and I am trying to do my project and I have an issue in that project. in my project, I have a view job button and whenever I click on any job or view job then it will redirect to another page and on that page, I want to show a full description of that job so please help me. thank you.
this is my views.py
def BrowseJob(request):
all_job = jobs.objects.all()
myFilter = jobsFilter(request.GET, queryset = all_job)
all_job = myFilter.qs
return render(request,'jobs.html',{'all_job':all_job,'myFilter':myFilter})
this is urls.py
from django.urls import path
from . import views
urlpatterns = [path('',views.index,name='index'),
path('Browse_Job',views.BrowseJob,name='Browse_Job'),
path('contact',views.contact,name='contact'),
path('job_details',views.jobdetails,name="job_details")]
this is my job.html
{% for job in all_job %}
<div class="job_lists">
<div class="row">
<div class="col-lg-12 col-md-12">
<div class="single_jobs white-bg d-flex justify-content-between">
<div class="jobs_left d-flex align-items-center">
<div class="thumb">
<img src="{{job.job_img.url}}" alt="">
</div>
<div class="jobs_conetent">
<h4>{{job.job_name}}</h4>
<div class="links_locat d-flex align-items-center">
<div class="location">
<p> <i></i>{{job.job_Category}}</p>
</div>
<div class="location">
<p> <i></i>{{job.job_Experience}}</p>
</div>
</div>
</div>
</div>
<div class="jobs_right">
<div class="apply_now">
View Job
</div>
<div class="date">
<p>Last Date for Apply: {{job.last_date}}</p>
</div>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
this is my jobdetails.html
{% for job in all_job %}
<img src="{{job.job_details.url}}" alt="">
{% endfor %}
please help me.
Actually to redirect in django using names in urls.py you need to write 'href' like this
<h4>{{job.job_name}}</h4>
Instead of
<h4>{{job.job_name}}</h4>
then it will work as you expected
refer this for more details :https://docs.djangoproject.com/en/3.1/ref/templates/builtins/

How to create a dynamic bootstrap carousel, using flask/python?

For context:
I'm building a social network. Just like with Facebook, each profile has a tab titled "images", which is a collection of thumbnails from the profile owner's posts.
My goal:
Just like with Facebook, I'd like the user navigating the page to be able to click on any thumbnail image, launching a bootstrap carousel and displaying that specific image in a much larger view. The user could then use the carousel-control class to scroll through the profile owner's other images.
Current situation:
The thumbnails display, you can click on any thumbnail and launch the carousel, but all of the profile owner's images appear stacked, as if they're all active.
I'm using a jinja2 for loop and a url_for statement to access the images. I also use a loop counter within an if statement to make it so only one image is active, but its obviously not working :(
It was this 4 year old stackoverflow post that I used to attempt solving this problem to begin with.
When using the carousel with a few images added statically it works properly, but I need it to be dynamic for obvious reasons.
I'm unsure how to go about showing just the specific image that was clicked on, and having the ability to scroll through the others.
Any help will be greatly appreciated!
Here is my HTML
<div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
{% for post in user.posts %}
{% if post.post_img != None %}
<div class="container">
<div class="item {% if loop.counter == 1 %} active {% endif %}" id="slide{{ loop.counter }}">
<img src="{{ url_for('static', filename='post_pics/' + post.post_img) }}">
</div>
<a class="carousel-control-prev" href="#pageCarousel" role="button" data-slide="prev">
<span class="carousel-control-prev-icon bg-primary" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#pageCarousel" role="button" data-slide="next">
<span class="carousel-control-next-icon bg-primary" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
{% endif %}
{% endfor %}
</div>
</div>
You can move the a tags outside the inner-carousel div, maybe like below ( its untested)
If you look at the documentaion, the a tags have to be outside.
<div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
{% for post in user.posts %}
{% if post.post_img != None %}
<div class="carousel-item {% if loop.index == 1 %} active {% endif %}" id="slide{{ loop.index }}">
<img src="{{ url_for('static', filename='post_pics/' + post.post_img) }}">
</div>
{% endif %}
{% endfor %}
</div>
<a class="carousel-control-prev" href="#pageCarousel" role="button" data-slide="prev">
<span class="carousel-control-prev-icon bg-primary" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#pageCarousel" role="button" data-slide="next">
<span class="carousel-control-next-icon bg-primary" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>

Issue with redirecting to various blog posts on click in django

I'm trying to create a simple blog which shows various articles on the homepage. The index page as of now holds the title and sub-title of various articles. I want it to display the entire content of the article on click. This is the error that I'm running into on the homepage.
NoReverseMatch at /
Reverse for 'article' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<article_id>[0-9]+)$']
This is the content of urls.py in the pages app that I've created.
from django.urls import path
from . import views
urlpatterns=[
path('',views.index,name='index'),
path('<int:article_id>',views.article,name='article'),
path('about',views.about,name='about'),
]
This is my views.py
from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse
from . models import Post
# Create your views here.
def index(request):
post=Post.objects.all()
context = {
'post' : post
}
return render(request,'pages/index.html',context)
def article(request,article_id):
article=get_object_or_404(Post,pk=article_id)
context = {
'article' : article
}
return render(request,'pages/article.html',context)
def about(request):
return render(request,'pages/about.html')
As you can probably see, I'm referring to the content of the articles through an article_id and the data regarding the particular post is fetched from the database.
This is my index.html, which should redirect to the content of the specific post on click.
{%extends 'base.html'%}
{%load static%}
{%block content%}
<!-- Page Header -->
<header class="masthead" style="background-image: url({% static 'img/home-bg.jpg' %})">
<div class="overlay"></div>
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<div class="site-heading">
<h1>Clean Blog</h1>
<span class="subheading">A Blog Theme by Start Bootstrap</span>
</div>
</div>
</div>
</div>
</header>
<!-- Posts -->
{% if post %}
{% for posts in post %}
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<div class="post-preview">
<a href="{% url 'article' article.id%}">
<h2 class="post-title">
{{posts.title}}
</h2>
{%if posts.subtitle%}
<h3 class="post-subtitle">
{{posts.subtitle}}
</h3>
{%endif%}
</a>
<p class="post-meta">Posted by
{{posts.postby}}
on {{posts.date}}</p>
</div>
<hr>
</div>
</div>
</div>
{% endfor %}
{%endif%}
<!-- Pager -->
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<div class="clearfix">
<a class="btn btn-primary float-right" href="#">Older Posts →</a>
</div>
</div>
</div>
</div>
<hr>
{%endblock%}
However though, I'm getting the required page when I type in localhost:8000/1 or localhost:8000/2 manually just like how I want it. But the problem is that, it does not redirect on click. My best guess is that this
<a href="{% url 'article' article.id%}">
is creating the problem.
All suggestions are welcome!.
Thank you.
You haven't got anything called "article" in that template. Your object is called "posts". So:
<a href="{% url 'article' posts.id %}">
(We'll leave aside the question of why you're calling your collection of posts "post" and each individual post "posts"...)

Categories