Multiple images are showing in django image grid - python

I am somewhat new to Django. I am making an image grid (html). But the images are shown multiple times in that grid. This is what I mean;
Here are my files;
Views.py
from django.shortcuts import render
photos = [
{
'user_im': 'https://thumbor.forbes.com/thumbor/fit-in/416x416/filters%3Aformat%28jpg%29/https%3A%2F%2Fspecials-images.forbesimg.com%2Fimageserve%2F5f47d4de7637290765bce495%2F0x0.jpg%3Fbackground%3D000000%26cropX1%3D1398%26cropX2%3D3908%26cropY1%3D594%26cropY2%3D3102',
'photo': 'https://images.unsplash.com/photo-1515199967007-46e047fffd71?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&auto=format&fit=crop&w=975&q=80',
'date_shared': '4th January, 2020',
'caption': 'A wonderful pic',
},
{
'user_im': 'https://cdn.britannica.com/67/19367-050-885866B4/Valley-Taurus-Mountains-Turkey.jpg',
'photo': 'https://images.unsplash.com/photo-1547500135-9f6e5a9a6aff?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&auto=format&fit=crop&w=1050&q=80',
'date_shared': '4th January, 2020',
'caption': 'A nice picture',
},
{
'user_im': 'https://cdn.britannica.com/67/19367-050-885866B4/Valley-Taurus-Mountains-Turkey.jpg',
'photo': 'https://i.guim.co.uk/img/media/6088d89032f8673c3473567a91157080840a7bb8/413_955_2808_1685/master/2808.jpg?width=1200&height=1200&quality=85&auto=format&fit=crop&s=412cc526a799b2d3fff991129cb8f030',
'date_shared': '4th January, 2020',
'caption': 'A nice picture',
}
]
def home(request):
context = {
'photos': photos,
}
return render(request, 'photos/home.html', context)
def explore(request):
context = {
'photos': photos,
}
return render(request, 'photos/explore.html', context)
grid.py
{% extends 'photos/base.html' %}
{% block content %}
<h1><strong>These are some of the best</strong></h1>
<h5 class="text-muted">Just for you...</h5>
{% for photo in photos %}
<div style="width:100%">
{% for photo in photos %}
<div style="float:left; width:200px; height:200px;">
<img src="{{ photo.photo }}" height="200px" width="200px">
</div>
{% endfor%}
</div>
{% endfor %}
{% endblock content %}
app urls.py
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('grid/', views.grid, name='grid'),
]
I am passing in some context. Will it be fixed if I upload the images?
Please give me a solution to this. Thank you.

This happens because you have done two loop. Use only once

They are showing up multiple times because you have a nested for loop. Pick one or the other, but not both, and you will end up with one of each image.
{% for photo in photos %} <-- loop one (for the rows)
<div style="width:100%">
{% for photo in photos %} <-- loop two (for the columns)
<div style="float:left; width:200px; height:200px;">
<img src="{{ photo.photo }}" height="200px" width="200px">
</div>
{% endfor%}
</div>

Related

How can I open a page with only one django model object's info after clicking it's ImageField on another page?

I am displaying django models on one of my website's pages. When I press one's ImageField on the page, I want it to open another page including only that one object. How do I do that ?
I thought about using the filter method in my views.py for filtering through my objects and finding that exact one, but I don't know what arguments to use.
Any ideas? (I am a beginner in django)
VIEWS.PY
from django.shortcuts import render
import requests
from . import models
def index(request):
return render(request, 'base.html')
def new_search(request): ********NOT IMPORTANT (I THINK)********
search = request.POST.get('search')
models.Search.objects.create(search=search)
objects = models.Object.objects.all()
results = objects.filter(name__contains=search).all()
args = { 'results': results }
return render(request, "my_app/new_search.html", args)
def individual_page(request):
link = request.GET.get('object-link')
objects = models.Object.objects.all()
return render(request, "my_app/individual_page.html")
MY TEMPLATE
{% extends "base.html" %}
{% block content %}
{% load static %}
<h2 style="text-align: center">{{ search | title }}</h2>
<div class="row">
{% for result in results %}
<div class="col s4">
<div class="card medium">
<div class="card-image">
<a name="object-link" href="{% url 'individual_page' %}"><img src="{{ result.image.url }}" alt=""></a>
</div>
<div class="card-content">
<p>{{result.name}}</p>
</div>
<div class="card-action">
View listing: Price TEST
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
So, the thing I want to do is: when I press the anchor tag that includes the image, I get redirectioned to another page which contains only that one object's info.

Models not displaying: unable to display models in site

anyone can help me with python django models, here is my code
models.py
class honeymoon(models.Model):
locationh = models.CharField(max_length=100)
imgh = models.ImageField(upload_to='locations')
detailh = models.TextField()
def __str__(self):
return self.locationh
views.py
def top10_honeymoon(request):
context = {
'posth': honeymoon.objects.all()
}
return render(request,'shop/honeymoon.html',context)
html
<div class="blog_list">
<h1 class="blog_heading"> Top 10 Destination For Honeymoon</h1><br><br>
<h2 class="blog_location">{{ posth.locationh }}</h2><br>
<img class="blog_img" src="{{ posth.imgh.url }}"><br>
<p class="blog_details">{{ posth.detailh }}</p><br><br>
</div>
admin.py
admin.site.register(honeymoon)
i'm trying to make model and trying to add some items from admin blog but its not displaying anything in my site, and not even showing the error. data is uploading from admin panel but its not displaying
you have to loop through the instances to see it
{% for obj in posth %}
<h2 class="blog_location">{{ obj.locationh }}</h2><br>
<img class="blog_img" src="{{ obj.imgh.url }}"><br>
<p class="blog_details">{{ obj.detailh }}</p><br><br>
{% endfor %}
try this :
<div class="blog_list">
<h1 class="blog_heading"> Top 10 Destination For Honeymoon</h1><br><br>
{% for post in posth.all %}
<h2 class="blog_location">{{ post.locationh }}</h2><br>
<img class="blog_img" src="{{ post.imgh.url }}"><br>
<p class="blog_details">{{ post.detailh }}</p><br><br>
{% endfor %}
</div>
Django cannot iterate itself. that's why you enable to show data.
You have to use for loop to show data in webpage
<div class="blog_list">
<h1 class="blog_heading"> Top 10 Destination For Honeymoon</h1><br><br>
{% for item in posth %} # add this
<h2 class="blog_location">{{ item.locationh }}</h2><br>
<img class="blog_img" src="{{ item.imgh.url }}"><br>
<p class="blog_details">{{ item.detailh }}</p><br><br>
{% endfor %} # add this
</div>

How to render links in a template for database filtering in django

I am using the "keyone" column in the database to filter entries. So far in the code i have written i am successfully able to render template with "keyone = 2" values. what should i write in a new template file, and how should i modify existing views.py so that when the template file renders it contains a list of links , each link for each value of "keyone" , when i click on the link say "keyone = 2", the selected entries should get rendered in home.html
models.py
# app/models.py
from django.db import models
from django.urls import reverse # new
class Post(models.Model):
text = models.TextField()
def __str__(self):
return self.text[:50]
keyone = models.IntegerField(default = '777')
def get_absolute_url(self): # new
return reverse('post_detail', args=[str(self.id)])
views.py
def HomePageView(request):
key2select = Post.objects.filter(keyone=2)
return render(request, 'home.html', {
'key2select': key2select,
})
home.html
<ul>
{% for post in key2select %}
<li>{{ post.keyone }}&nbsp &nbsp{{ post.text }}</li>
{% endfor %}
</ul>
sample database
desired rendering
Firstly, we need to get all keyone values in the DB, to be passed to home.html.
Then in home.html, we need a navbar or somewhere else to put all these links which represent all the keyone values.
So the code would be like:
models.py
# app.models.py would remain the same
views.py
def homePageView(request, key):
key2select = Post.objects.filter(keyone=key)
keyones = Post.objects.distinct('keyone')
return render(request, 'home.html', {
'key2select': key2select,
'keyones': keyones
})
You can check the distinct() in the Django Docs to get distinct values of a column in DB
home.html
<!-- home.html -->
<nav>
<ul>
{% for key in keyones %}
<li>somthing {{key}} something</li>
{% endfor %}
</ul>
</nav>
...
<ul>
{% for post in key2select %}
<li>{{ post.keyone }}&nbsp &nbsp{{ post.text }}</li>
{% endfor %}
</ul>
As we passed the key to the url in the nav link, we need to change the url pattern to catch this.
urls.py
urlpatterns =[
...
path('home/<int:key>/', views.homePageView, name='home')
...
]
May be I'm not understand you problem, if you'r looking for create a list of link code should be
<ul>
{% for post in key2select %}
<a href="{% url "post_detail" post.id %}"><li>{{ post.keyone }}&nbsp &nbsp{{ post.text }}</li><a/>
{% endfor %}
</ul>
This will contain every post link with list item
thanks #sheng-zhuang for providing the solution. Here is the working code with some slight modifications for my benefit.
I created a new template select.html and here is the logic -
Views.py
class IndexView(TemplateView):
template_name = 'index.html'
def SelectView(request):
keyones = Post.objects.values_list('keyone',flat=True).distinct()
return render(request, 'select.html', {
'keyones': keyones
})
def HomePageView(request, key):
key2select = Post.objects.filter(keyone=key)
return render(request, 'home.html', {
'key2select': key2select,
})
index.html
<header>
Select<br />
Post
</header>
select.html
<nav>
<ul>
{% for key in keyones %}
<li>Keyone value = {{key}} </li>
{% endfor %}
</ul>
</nav>
home.html
<header>
Select<br />
Post
</header>
<br /><br /><br /><br />
<ul>
{% for post in key2select %}
<li>{{ post.keyone }}&nbsp &nbsp{{ post.text }}</li>
{% endfor %}
</ul>
urls.py
path('', IndexView.as_view(), name='index'),
path('select/', SelectView, name='select'),
path('home/<int:key>/', HomePageView, name='home')

CSS fails when passing a list to render(request)

I am trying to follow a tutorial online and for some reason I cannot get css to work correctly with my views.py file and django 2.2. when I remove the "My_context" from return render(request, 'blog/home.html', My_context)
and pass something else like
return render(request, 'blog/home.html', {'title': 'blah') it seems to work just fine.
I have tried restarting the server and and clearing the page cache. I am new to django and not sure what else to try.
views.py
from django.shortcuts import render
posts = [
{
'author': 'xxxxx',
'title': 'Blog Post 1',
'Content': 'My First Post Content',
'date_posted': 'August 27, 2019'
},
{
'author': 'xxxxx',
'title': 'Blog Post 2',
'Content': 'My Second Post Content',
'date_posted': 'August 27, 2019'
}
]
# This function fails to load css correctly
def home(request):
My_context = {
'posts': posts
}
return render(request, 'blog/home.html', My_context)
#This function works fine
def about(request):
return render(request, 'blog/about.html', {'title': 'About'})
home.html
{% extends "blog/base.html" %}
{% block content %}
{% for post in posts %}
<h1>{{ post.title }}</h1>
<p>By {{ post.author }} on {{ post.date_posted }}</p>
<p>{{ post.Content }}</p>
{% endfor %}
{% endblock content %}
about.html
{% extends "blog/base.html" %}
{% block content %}
<h1>About Page</h1>
{% endblock content %}
The major difference between home() and about() is the template you use.
So you should check your home.html contains the path to your css file.
You can also check your console for any error message and share it with us.

Image not showing in for loop

I am trying to display the image and name in a for loop on my template.
This is what I have on my template for loop, and I thought it should work, but it doesn't
{% for op in tracked_objects %}
{% if op.is_mine %}
<div style="float:left;">
<div>
<img src="{{ op.tracked_object.image }}" alt="">
<a href='{% url track-profile op.tracked_object.id %}'>{{ op.tracked_object }}</a><br>
</div>
</div>
{% endif %}
{% endfor %}
I know that op.is_mine is true because the Name shows.
Here is my views.py:
#login_required
def profile(request):
user = request.user
tracked_objects = user.tracked_object_perms.all().order_by('is_mine',)
context = {
'tracked_objects':tracked_objects,
}
return render_to_response( 'accounts/profile.html' , RequestContext(request, context))
and finally the models.py
name = models.CharField(max_length='140')
image = models.ImageField(upload_to='img/tracked_object_images', null=True, blank=True)
Update
Now when I use the below anser of adding the .url onto the end, I get three broken image icons. Now I have checked the path and it goes to the correct image. Would this be a server issue possibly? Or something along those lines?
Try:
<img src="{{ op.tracked_object.image.url }}" alt="">
See Using django.contrib.staticfiles.

Categories