1

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!!

2
  • Do you only want the latest post? If so, you don't need to use a for loop in the first place Commented Apr 25, 2017 at 15:30
  • it returns the html without the loop, but doing {{ latestPost.title }} etc... does not display the content in the views. am I missing something ?? Commented Apr 25, 2017 at 15:51

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I unfortunately think this is not the problem, I might be missing something somewhere. I have tried your suggestion, but it still returns the html with missing database items!!! it's extremely frustrating because I know the problem is something small, I appreciate the tip on the first() last() though! did not know that.
try rerun python manage.py makemigrations then python manage.py migrate. Please backup your database before attempting in case @Fanna1119
My problem was I did something wrong in a model that did not read the model if it was not "published" , however your answer was also part of the solution, rendering to the blog_index.html instead of latest_post.html which makes a lot of sense actually, it renders the index and gathers via {% include %} Thank you!
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

1 Comment

I tried it like this but strangely enough it still does not return anything??with and without the for loop, I am so confused at the moment. it does return the html but the content & title and everything is empty.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.