R
R
rusyska550112021-02-05 15:26:32
Django
rusyska55011, 2021-02-05 15:26:32

How to not display an image if it does not exist?

views.py method:

def index(request):
    content = News.objects.all()

    for el in content:
        el.picture = '/' + str(el.picture).split('/')[-1]

    context = {
        'content' : content
    }

    return render(request, 'News.html', context)


Database:
601d382cdb7e2996499944.png

Output:
601d389f8a056505784604.png

HTML code:
<body> 
    <h1> News </h1>
    {% for el in content %}

      <h1><a href = "/news/{{el.pk}}"> {{ el.title }} </a></h1>
        
      <img src = "{% static 'pictures' %}{{el.picture}}", width="100", height="100">
      
      <p> {{el.content}} </p>
      <p> {{el.published}} </p>
      <a href = "/news/rubric№{{el.rubric.pk}}"> {{el.rubric}} </a>

    {% endfor %}
  </body>


I tried to do this, but then it just does not display the picture:
{% if el.picture != "" %}	
  <img src = "{% static 'pictures' %}{{el.picture}}", width="100", height="100">
{% endif %}


Also tried this:
{% if ".jpg" in el.picture %}	
  <img src = "{% static 'pictures' %}{{el.picture}}", width="100", height="100">
{% endif %}


For some reason, the constructions do not give out anything, the images do not appear at all

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2021-02-05
@bacon

Who draws an image like that?
Throw it away, here it is

for el in content:
    el.picture = '/' + str(el.picture).split('/')[-1]

and do it in the template , and it's quite simple Threat and for /news/{{el.pk}} and other hrefs to kick too, and then send them to read the docks. {{ el.picture.url }}{% if el.picture %}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question