我正在尝试仅显示首页的第一个最新帖子,但仍然循环所有。请我需要帮助这是view.py:
def index(request):
context = {
'infos': info.objects.all(),
}
return render(request, 'blog/index.html',context)
index.html我想知道从数据库发布时如何仅显示最新发布
<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)
您只需要简单地更改查询:
def index(request):
context = {
'info': info.objects.('-date_posted').first(),
}
return render(request, 'blog/index.html', context)
然后从模板中删除for
循环:
<!-- {% for info in infos %} -->
和类似的东西现在将起作用:
{{ info.title }} # things like this will now work
代替info.objects.all()
,使用info.objects.order_by('-date_posted').first()
仅获取最新发布的info
对象。
<!-- ... -->
是HTML注释,如果将Django命令放入其中,它们仍将执行。尝试改用{% comment %}...{% endcomment %}
。
否则,为什么只想显示第一个对象就提取所有对象?
如果我是你,我会做的:
def index(request):
context = {
'infos': info.objects.filter(published__is=True).order_by('date_posted').first(),
}
return render(request, 'blog/index.html',context)
使用它,您当然不需要for循环。
希望这会有所帮助!
def index(request):context = {'infos':info.objects.order_by('-date_posted')。first(),}返回render(request,'blog / index.html',上下文)