Django load an imageField in a template - python

Essentially what I'm trying to do is load the thumbnail image from my Post model in my template.
models.py
class Post(models.Model):
objects = models.Manager() # The default manager.
published = PublishedManager() # Our custom manager.
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique_for_date='publish')
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='blog_posts')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
thumbnail = models.ImageField(name="photo", upload_to='thumbnails/', null=True, default='default.png')
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug])
views.py
class PostListView(ListView):
queryset = Post.published.all()
context_object_name = 'posts'
paginate_by = 3
template_name = 'blog/post/list.html'
def get_context_data(self, **kwargs):
obj = Settings.objects.get(pk=1)
context = super().get_context_data(**kwargs)
context["blog_name"] = getattr(obj, "blog_name")
context["footer"] = getattr(obj, "footer")
context["description"] = getattr(obj, "description")
context["keywords"] = getattr(obj, "keywords")
return context
I added <img src="{{post.thumbnail.url}}" alt="{{ post.title }}"> to my template to try and load the image but no luck. I can access the image if I load the path manually and i already added MEDIA_URL and MEDIA_ROOT to my settings.py
If this question can be improved please let me know as I am knew to django.
template
<header>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script type='text/javascript'>
window.addEventListener('scroll', function() {$('#top-bar').width(Math.round($(document).scrollTop()/document.body.offsetHeight*100*1.1)+'%');});
</script>
<div id='top-bar'></div>
<h1 id='title'>{{ post.title }}</h1>
<p id='author-info'>Published {{ post.publish }} by {{ post.author }}</p>
</header>

One thing that I would check first is to make sure the URL is actually showing up correctly in the template. You can do that by just creating a dummy span like this:
<span>{{ post.thumbnail.url }}</span>
Put that somewhere, render the page and see what you get. Ensure that the URL is the correct URL. Sometimes when you're messing with media URLs and roots, things get a bit wonky.
UPDATE:
Based on your recent edits, I see two red flags: One is that you've got your body up in your header section. Two is that it doesn't appear that you're iterating through the list of objects that are being passed as context by your ListView. Your listview, as i interpret it, is passing a list of posts. If that's the case, your code should look something like this:
<header>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script type='text/javascript'>
window.addEventListener('scroll', function() {$('#top-bar').width(Math.round($(document).scrollTop()/document.body.offsetHeight*100*1.1)+'%');});
</script>
</header>
<body>
<div id='top-bar'></div>
{% for post in posts %}
<h1 id='title'>{{ post.title }}</h1>
<p id='author-info'>Published {{ post.publish }} by {{ post.author }}</p>
<img src="{{ post.thumbnail.url }}">
{% endfor %}
</body>
Still, there is something a bit off about your whole HTML document. You'll need to add in DIV elements or grid table elements to more appropriately render the above stuff.

Another thing: Since your'e using a list view, you might want to post a portion of your template code here in your question. As a list view, you have to ensure that you're properly looping through the object you're sending to the template as context.
Is everything else showing up in your template rendering as you intend? Is it just the image that isn't showing properly?

Related

Django: how to create a dictionary of objects and display in templates

Hey I have had a look at similar questions but none really relate to what I am trying to do, they either explain how to order things in the admin panel or simply iterating over object dictionaries.
I have created a basic photo model that contains a value gallery_order so I can edit them in Admin.
I wish to populate my template with the pictures according to the gallery_order values in order from 1 upward.
I guess the best way to handle it is with a dictionary but I do not know where to initialize it, if I put it in the picture model then each picture holds a dict with all the pictures order number and url in it which seems mental.
My current model:
class Picture(models.Model):
title = models.CharField(max_length=36, blank=False, unique=True)
gallery_order = models.IntegerField(default=0)
image = models.ImageField(upload_to='photos/', blank=False)
def __str__(self):
return self.title
My template code:
<head>
<meta charset="utf-8">
{% block content %}
<div class="row">
{% if pictures %}
{% for picture in pictures %}
<div class="col-md-12">
<div class="card mb-0">
<img class="card-img-top" src="{{ picture.image.url }}">
</div>
</div>
{% endfor %}
{% endif %}
</div>
{% endblock content %}
</head>
my admin code:
#admin.register(Picture)
class PictureAdmin(admin.ModelAdmin):
list_display = ('gallery_order', 'title', 'image')
list_display_links = ['gallery_order']
search_fields = ['title']
def get_queryset(self, request):
queryset = super(PictureAdmin, self).get_queryset(request)
queryset = queryset.order_by('gallery_order')
return queryset
I tried to figure out how django was displaying them by looking at the PK in psotgres db but it seems to simply display them according to last edited.
Thank You :)
You could also do this at the model level by adding the following at the end of your model.
class Meta:
ordering = ['gallery_order']
I am so silly sometimes I forgot about my views!
all I had to do was specify order_by for goodness sake...
class Home(View):
pictures = Picture.objects.all().order_by('gallery_order')
def get(self, request):
return render(request, 'home.html', {'pictures': self.pictures})

how to show the field data of one app model on the other app template?

Well, I am creating a user profile where the user can see his all posts which he has been uploaded. But I don't understand one thing that how could I possibly grab the fields of Post model from Posts/models.py and show them on the template which I have created in another app (Profiles) templates.
The reason I am trying to access them on other app is that I want to show them in the userprofile.html template. Just like Facebook posts. And please tell me if you know that it is not possible with django?
posts/models.py :
class Post(models.Model):
username = models.ForeignKey(User, verbose_name=("user name"), on_delete=models.CASCADE)
description = models.CharField(('Description'),max_length=250)
title = models.CharField(('Content Title'), max_length=250)
create_date = models.DateTimeField(default = timezone.now)
image_data = models.ImageField(upload_to='User_Posts', height_field=None, width_field=None, max_length=None)
def __str__(self):
return self.title
profiles/views.py
from posts.model import Post
from django.views.generic import ListView
class UserPostListView(ListView):
model = Post
context_object_name = 'userpost_list'
template_name = 'profiles/userprofile.html'
def get_queryset(self):
user = get_object_or_404(User, username = self.kwargs.get('username'))
return Post.object.filter(username = user).order_by('-create_date')
profiles/templates/profiles/userprofile.html
<div class="jumbotron">
{% for post in userpost_list %}
<div class="post">
<h1>{{ posts.post.title }} <img src="" alt="not found" height="60" width="60" style="float:right ;border-radius: 20px;" ></h1>
<div class="date">
<p>
<!-- Published on: {{ object.author.post.create_date|date:"D M Y" }} -->
</p>
</div>
</div>
{% endfor %}
</div>
</div>
You can access any app from any other app. You just need to do the necessary model imports which you are doing. Looks like you just need to tweak your line of code in the template from:
<h1><a href="">{{ posts.post.title }}...
to:
<h1><a href="">{{ post.title }}...
and when you decide to use it.
<!-- Published on: {{ object.author.post.create_date|date:"D M Y" }} -->
to:
<!-- Published on: {{ post.create_date|date:"D M Y" }} -->
The reason is that your queryset is returning a dataset of the Post model. So you are already in it.
It just done by importing model from the app you want to use model to other app. And that it. This is python OOP(object oriented programming) concept.

Django Getting Data From Foreign Key

Im a newbie working on a news site (or at least trying to, a lot of "problems" in the last few days lol ) trying to learn Django the best I can.
This is what I want to do :
I have an Article Model, it used to have 6 image fields that I used to send to the template and render the images, each image field had its own name and all was well in the world.
Then I got tasked with puting the Article images in a separate Image model.
So I did this :
class Article(models.Model):
title = models.CharField('title', max_length=200, blank=True)
slug = AutoSlugField(populate_from='title', default="",
always_update=True, unique=True)
author = models.CharField('Author', max_length=200, default="")
description = models.TextField('Description', default="")
is_published = models.BooleanField(default=False)
article_text = models.TextField('Article text', default="")
pub_date = models.DateTimeField(default=datetime.now, blank=True)
article_category = models.ForeignKey(Category, on_delete="models.CASCADE", default="")
def __str__(self):
return self.title
class ArticleImages(models.Model):
article = models.ForeignKey(Article, on_delete="models.CASCADE", related_name="image")
image = models.ImageField("image")
name = models.CharField(max_length=50, blank=True)
But so far I wasnt able to access my images in my template using
{{ article.image.url }} or {{ article.image.image.url }}
or any other combination. Why is that ?
Did I set up my models correctly ? One person suggested that I should change the model field from ForeignKey to OneToOneField, but I didn't get much feedback on why and how ?
So, how would I make a for loop that loops through the Articles model and then gets the related images for each Article ? I essentially want it to behave like I still have the 6 different fields like I did before. ( I have to do it this way, it's a part of the task ).
here are my views and my "index" template that I used to loop through the Articles and display 6 latest news on my home page. (please ignore the tags,I am aware they aren't working like this..the template is just so you can understand what I am talking about )
my views.py:
class IndexView(generic.ListView):
template_name = 'news/index.html'
context_object_name = 'latest_article_list'
def get_queryset(self):
return Article.objects.all()
class CategoryView(generic.ListView):
template_name = 'news/categories.html'
context_object_name = 'category'
def get_queryset(self):
return Article.objects.filter(article_category__category_title="Politics")
class ArticlesView(generic.ListView):
context_object_name = 'latest_article_list'
template_name = 'news/articles.html'
paginate_by = 5
def get_context_data(self, **kwargs):
context = super(ArticlesView, self).get_context_data(**kwargs)
context['categories'] = Category.objects.all()
return context
def get_queryset(self):
category_pk = self.request.GET.get('pk', None)
if category_pk:
return Article.objects.filter(article_category__pk=category_pk).order_by("-pub_date")
return Article.objects.order_by("-pub_date")
def article(request, article_id):
article = get_object_or_404(Article, pk=article_id)
context = {'article': article,
'article_category': article.article_category.category_title}
return render(request, 'news/article.html', context)
template that I used with my old model :
{% for article in latest_article_list %}
<img class="single-article-img" src="{{ article.image.name.url }}" alt="">
<div class="container row">
<!-- Start Left Blog -->
<div class="article mt-10 col-md-4 col-sm-4 col-xs-12">
<div class="single-blog" style="margin:10px auto;">
<div class="single-blog-img">
<a href="{% url 'news:article' article.id %}#article-title">
<img class="for-imgs" src="{{ article.image.url }}" alt="">
</a>
</div>
<div class="blog-meta">
<span class="date-type">
<i class="fa fa-calendar"></i>{{ article.pub_date }}
</span>
</div>
<div class="xx blog-text">
<h4>
{{ article.title }}
</h4>
<p>
{{ article.description|truncatewords:30 }}
</p>
</div>
<span>
Read more
</span>
</div>
</div>
{% endfor %}
Thank you !
You need to loop over the images as you have many images against a single article object. You can have something like below to show images in your template:
{% if latest_article_list.articleimages %}
{% for articleimage in latest_article_list.articleimages.all %}
<img src="{{ articleimage.image.url }}" class="d-block w-100" alt="...">
{% endfor %}
{% endif %}

Search Field in Django Python

First, I have to say that is this my first application in Django. So my knowledge is still limited.
I have this home page where it shows all the data in my model. The model name is "Asset".
I am trying to have a search field inside the home page.
models.py
class Asset(models.Model):
asset_desc = models.CharField(max_length=120, null=False)
BEIRUT = 'Beirut'
SAIDA = 'Saida'
HALBA = "Halba"
base_choice = ((SAIDA, "Saida"), (BEIRUT, "Beirut"), (HALBA, "Halba"))
asset_base = models.CharField(max_length=120, null=False, choices=base_choice)
created_date = models.DateField(auto_now_add=True)
update_date = models.DateTimeField(auto_now=True)
asset_user = models.CharField(max_length=120, blank=True)
slug = models.SlugField()
def save(self, *args, **kwargs):
self.slug = slugify(self.asset_desc)
super(Asset, self).save(*args, **kwargs)
def __str__(self):
return self.asset_desc
views.py
def search_asset(request):
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
assets = Asset.objects.filter(asset_desc__icontains=q)
context = {'desc': assets}
return render(request, 'home.html', context)
html for the search field:
<form method="GET" class="navbar-form navbar-right">
<input type="text" class="form-control" placeholder="Search..."id="search_box" name="q">
urls.py
url(r'^search/$', "asset.views.search_asset", name="home")
Please any help on why it is not showing the result. I am using Django 1.9.
some corrections:
you dont need null=False for TextField() and CharField(), since they never save Null to database but empty string. so you can remove null=False
the search url name is home which logically not really approriate. it should be changed to search or search_view and then you can refer to it via url tag:
action="{% url 'search' %}"
this is useful if someone should look over your code. "Readability counts" ;)
and finally, put this to your home.html (actually you must already have it)
{% for asset in desc %}
<div>
{{ asset.asset_desc }} <br>
{{ asset.base_choice }} <br>
{{ asset.asset_user }}
</div>
{% endfor %}
I hope, this helps
You have not provided the template or the HTML portion where you list the results. You should consider the name of you context variable, but by following your name, you should list the results like this:
{% for asset in desc %}
<div>
{{ asset }}
</div>
{% endfor %}
Anything else looks correct.
Hope it helps

Django: Querying to ImageField all images are being rendered

So my problem is that when I try to query to the image url so it can be posted to its corresponding Post all the images that have been uploaded to the media folder is being rendered, even though in the admin panel it shows that each post has it's own image and they are assigned to different posts, instead all of them are being rendered together for each and every post.
The models that I have are SellPost which is for creating a post and SellPostImage is for assigning the image to the post.
models.py
class SellPost(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=128)
category = models.ForeignKey(Category)
type = models.ForeignKey(SellPostType, default=None)
body = models.CharField(max_length=400)
price = models.DecimalField(decimal_places=1, max_digits=5, default=0.0)
views = models.IntegerField(default=0)
likes = models.IntegerField(default=0)
slug = models.SlugField(unique=True, default='automatic')
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(SellPost, self).save(*args, **kwargs)
def __unicode__(self):
return self.title
class SellPostImage(models.Model):
user = models.ForeignKey(User, null=True)
post = models.ForeignKey(SellPost)
pictures = models.ImageField(upload_to='post_images', blank=True)
def __str__(self):
return "{}".format(self.post)
class Meta:
verbose_name_plural = "Post Images"
In the view I tried to create a context dict (because I'm a newbie in Django and have learned that from Tango with Django so I went with it) for the post and then the images:
views.py
def post(request, post_name_slug):
context_dict = {}
try:
post = SellPost.objects.get(slug=post_name_slug)
context_dict['post'] = post
post_image = SellPostImage.objects.all()
context_dict['post_image'] = post_image
except SellPost.DoesNotExist:
pass
return render(request, 'p.html', context_dict)
and here is how I tried to render them in the HTML file.
p.html
<ul>
{% for post in posts %}
<li>{{ post.title }} </li>
{% for post_images in post_image %}
<img style="width:200px; height:200px;" src="{{ post_images.pictures.url }}" />
{% endfor %}
{% endfor %}
</ul>
You'll want to filter the SellPostImage for the retrieved post:
post = SellPost.objects.get(slug=post_name_slug)
context_dict['post'] = post
post_image = SellPostImage.objects.filter(post=post)
context_dict['post_image'] = post_image
But you can just as easily put that logic part directly into your template:
{% for post in posts %}
<li>{{ post.title }} </li>
{% for post_images in post.sellpostimage_set.all %}
<img style="width:200px; height:200px;" src="{{ post_images.pictures.url }}" />
{% endfor %}
{% endfor %}
and then you can remove the SellPostImage in your views:
try:
post = SellPost.objects.get(slug=post_name_slug)
context_dict['post'] = post
except SellPost.DoesNotExist:
pass
In your post method you query for all SellPostImages:
post_image = SellPostImage.objects.all()
That's why you get all images for each post.
You can filter only the images associated with a post by doing the following instead:
post_image = SellPostImage.objects.filter(post=post)
It will provide all images for that specific post.

Categories