Reputation: 23
i am trying to show only the first latest post the main page but still loops all. please i need help this is the view.py:
def index(request):
context = {
'infos': info.objects.all(),
}
return render(request, 'blog/index.html',context)
index.html i want to know how to show only the latest post when is posted from the database
<div class="img-border">
<!-- {% for info in infos %} -->
<a href="{{ infos.video.url }}" class="popup-vimeo image-play">
<span class="icon-wrap">
<span class="icon icon-play"></span>
</span>
<img src="{% static 'blog/images/img_2.jpg' %}" alt="" class="img-fluid">
</a>
</div>
</div>
<div class="col-md-5 ml-auto">
<span class="caption px-0 text-muted">Latest Sermon</span>
<h2 class="h2 mb-0">{{ infos.title }}</h2>
<span class="d-block mb-3"><em>by</em> {{ infos.author }}</span>
<p class="h5 mb-2">If ye love Me, keep My Commandments.</p>
<p class="mb-4 word-wrap1">{{ infos.content }}</p>
<p><a href="{{ infos.video.url }}" class="popup-vimeo text-uppercase">Watch Video <span class="icon-arrow-right small"></span></a></p>
<!-- {% endfor %} -->
</div>
</div>
</div>
</div>
model.py
class info(models.Model):
image = models.ImageField(upload_to='profile_pics')
video = models.FileField(upload_to="videos")
title = models.CharField(max_length= 100)
content = models.TextField()
author = models.CharField(max_length=15)
date_posted = models.DateTimeField(default = timezone.now)
published = models.BooleanField(default=True)
Upvotes: 0
Views: 108
Reputation: 4432
You need to simply change your query:
def index(request):
context = {
'info': info.objects.order_by('-date_posted').first(),
}
return render(request, 'blog/index.html', context)
Note: ordering by
date_posted
was proposed by Toni Sredanović in other answer, but since it's defaults tonow
it'll anyway follow the ID's ordering so could be simplified to justinfo.objects.last()
.
then remove for
loop from template:
<!-- {% for info in infos %} -->
and things like this will now work:
{{ info.title }} # things like this will now work
Upvotes: 1
Reputation: 718
def index(request):
context = {'infos': info.objects.order_by('-date_posted').first(),}
return render(request, 'blog/index.html', context)
Upvotes: 0
Reputation: 592
<!-- ... -->
is an HTML comment, if you put Django command inside, they will still be executed. Try using {% comment %}...{% endcomment %}
instead.
Otherwise, why do you fetch all objects when you only want to display the first one?
I'd do if I were you:
def index(request):
context = {
'infos': info.objects.filter(published__is=True).order_by('date_posted').first(),
}
return render(request, 'blog/index.html',context)
Using this you won't need the for loop of course.
Hope this helps!
Upvotes: 0
Reputation: 2412
Instead of info.objects.all()
use info.objects.order_by('-date_posted').first()
to get only the latest posted info
object.
Upvotes: 1