Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

144
Vistas
Django for loop in html template not displaying

So I am trying to get the latest post and I ran into a problem where it will not display the post

views.py

def latest_post(request):
    latest = Post.objects.all().order_by('-id')[:1]
    context = {'latestPost': latest}
    return render(request, 'latest_post.html', context)

Note: I also tried it with this, latest = Post.objects.all()

There are entries in the database, I tested with the shell

from blog.models import Post
>>> Post.objects.all()
<QuerySet [<Post: test>, <Post: okay so>, <Post: okay-okay>]>

latest_post.html

{% for newest in latestPost %}
<section class="hero is-primary is-medium">
  <div class="hero-body header">
    <div class="container">
     <div class="font">
      <h1 class="title is-1">
        <span id="blog_title">{{ newest.title }}</span>
      </h1>
      <h2 class="subtitle is-3 subup">
        <span id="blog-subtitle">{{ newest.content|truncatechars:20|safe }}</span>
      </h2>
      <h2 class="subtitle is-5 dateup">
        <span id="blogdate">{{ newest.timestamp }}</span><br><br>
        <a href="{{ newest.blog_url }}" class="button is-danger is-large is-inverted">Read More >></a>
      </h2>
    </div>
    </div>
  </div>
</section>
{% endfor %}

in my blog_index.html I have the following

{% extends "blog_base.html" %}
{% block blog_main %}
{% load staticfiles %}

{% include 'latest_post.html' %}
<p> other html here </p>
{% endblock %}

Latest_post.html displays when i use {% include 'latest_post.html' %} only if I don't use

{% for newest in latestPost %}
{% endfor %}

So i am sure there aren't any typos somewhere that prevents the latest_post.html from displaying in my index page.

my models.py

class Post(models.Model):
    title = models.CharField(max_length=120)
    slug = models.SlugField(unique=True)
    content = models.TextField()
    draft = models.BooleanField(default=False)
    publish = models.DateField(auto_now=False, auto_now_add=False)
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

    def __str__(self):
       return self.title

    def blog_url(self):
        return reverse("blogposts:blogdetail", kwargs={"slug": self.slug})

Additional Notes: python3, django 1.11, sqlite. Also, No errors are displayed in the console. any help would be appreciated! thank you!!

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Looks like you are passing context variable to latest_post.html directly:

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

But there is no such context variable latestPost in blog_index.html. What you need to do is add context to blog_index.html. Add this to index view also:

latest = Post.objects.all().order_by('-id')[:1]
context = {'latestPost': latest}
return render(request, 'blog_index.html', context)

Also you can use first to select first element in queryset.

over 4 years ago · Santiago Trujillo Denunciar

0

In your previous code you are limiting it by using [:1] so it only returns one item. Then you are using a forloop again on one item. Not the best way to do things.

Are you trying to get only one item from the post? If yes, Forloop is not needed change your latest_post.html to

<section class="hero is-primary is-medium">
  <div class="hero-body header">
    <div class="container">
     <div class="font">
      <h1 class="title is-1">
        <span id="blog_title">{{ latestPost.title }}</span>
      </h1>
      <h2 class="subtitle is-3 subup">
        <span id="blog-subtitle">{{ latestPost.content|truncatechars:20|safe }}</span>
      </h2>
      <h2 class="subtitle is-5 dateup">
        <span id="blogdate">{{ latestPost.timestamp }}</span><br><br>
        <a href="{{ latestPost.blog_url }}" class="button is-danger is-large is-inverted">Read More >></a>
      </h2>
    </div>
    </div>
  </div>
</section>

You don't even need to use the [:1] in your views. There are better ways to do this

over 4 years ago · Santiago Trujillo Denunciar

0

I also stuck in the same problem and I was damn confirmed that I was doing any silly mistakes.

Unfortunately, I found one. So, Try this:

context = {'latest': latest}

Instead of:

context = {'latestPost': latest}

I hope it works.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda