TheCodingRecruiter
TheCodingRecruiter

Reputation: 71

How to use if statement inside a block in Django for image retrieval

I'm stuck. I have been trying to use all of my google fu to find this answer, but can't find it asked or answered anywhere. This is one of my first projects that I am trying to do not following a tutorial, so I apologize for my ignorance ahead of time. I am building my first blog and am trying to add a feature to display an image in the article. The problem is, I only want it to display if there is an image, as not all of them will have images. I can get the image to display, but if I go to an article without one, it gives me an error saying that it can't find the image. I thought I would try to do an if statement, but I am getting an error there as well and am not sure if I am doing the statement incorrectly (which is my guess) or not.

#models.py
from django.db import models
from datetime import datetime

# Create your models here.

class Post(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField()
    created_at = models.DateTimeField(default=datetime.now, blank=True)
    image      = models.ImageField(upload_to='blog/', null=True, blank=True)

    def __str__(self):
        return self.title




#view.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Post

# Create your views here.
def index(request):
    posts = Post.objects.all()[:10]

    context = {
        'title' : 'Latest Posts',
        'posts' : posts,
    }

    return render(request, 'blog/index.html', context)

def details(request, id):
    post = Post.objects.get(id=id)
    queryset = Post.objects.all()

    context = {
        'post' : post,
        'object' : queryset
        }

    return render(request, 'blog/details.html', context)




#details.html
{% extends 'blog/layout.html'%}

{% block content %}
<h3 class="center-align red darken-3">{{post.title}}</h3>
<div class="card hoverable">
    <div class="card-content teal accent-4">
        {{post.body}}
    </div>
    <div class="card-action teal accent-4">
        {{post.created_at}}
    </div>

    {% if post.image.url %}

    {% for post_image in post.image.url %}

    <div class="div">
        <img src='{{post.image.url}}' class='responsive-img' /><br/>  
    </div>
    {% else %}
    <div class="div">
        </div>

    {% endfor %}
    {% endif %}
</div>
<a href="/blog/" class="btn">Go Back</a>

{% endblock %}

Upvotes: 0

Views: 39

Answers (1)

Sam
Sam

Reputation: 2084

Try the below!

{% if post.image != '' %}

    <div class="div">
        <img src='{{post.image.url}}' class='responsive-img' /><br/>  
    </div>
{% else %}
    <div class="div">
        </div>
{% endif %}

Upvotes: 1

Related Questions