如何使用Django Python显示我的最后3篇文章
我试图用Django显示我的最后3篇文章,但我的3篇文章没有出现在我的页面上。这是我的密码。 我没有错误或任何东西,当我加载页面和我的其他帖子出现在我的页面上。 请客气一点,这是我第一次使用Python和Django=) models.py 意见 我的网址 模板html(post_list.html) 但是这三篇文章没有出现在我的页面上这是你的问题如何使用Django Python显示我的最后3篇文章,python,django,python-3.x,post,Python,Django,Python 3.x,Post,我试图用Django显示我的最后3篇文章,但我的3篇文章没有出现在我的页面上。这是我的密码。 我没有错误或任何东西,当我加载页面和我的其他帖子出现在我的页面上。 请客气一点,这是我第一次使用Python和Django=) models.py 意见 我的网址 模板html(post_list.html) 但是这三篇文章没有出现在我的页面上这是你的问题 def latest_posts(request): latests = Post.objects.filter(published_dat
def latest_posts(request):
latests = Post.objects.filter(published_date__lte=timezone.now()).reverse()[:3]
return render(request, 'blog/post_list.html', {'latest': latest})
您在第2行定义了latest
,但在第3行通过了latest
。然后在模板中,您已恢复为最新版本,因此您需要:
def latest_posts(request):
latests = Post.objects.filter(published_date__lte=timezone.now()).reverse()[:3]
return render(request, 'blog/post_list.html', {'latests': latests})
我终于发现了我的错误。我试图在一个def中返回两个def,但它不能像那样工作。我将两个返回合并为一个,它成功了!谢谢大家帮助我:)欢迎来到SO。打破使用“它不起作用”的习惯。这对任何人都没有意义,因为它没有描述你的问题是什么。你说没有错误。页面上有什么显示吗?所有帖子都显示在页面上吗?另外,您使用latest作为变量名,然后将latest作为上下文传递。在你的“最新发布”视图中是否正确?你似乎没有最新发布的URL。你怎么称呼它?你确定这篇文章设置了一个发布日期(不是空的)?您确定这些日期小于
时区。now()
?@DanielRoseman否没有最新发布的URL。我应该如何创建正确的URL?你好,HenryM,非常感谢你的回答!但当我重新加载修改后的页面时,并没有任何变化。你还有别的想法吗?
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
]
<div id="container">
{% for latest in latests %}
<article class="lastnews">
<h4>{{ latest.title }}</h4>
<h5 class="lastestcategory">{{ latest.category }}</h5>
<p class="bodysmall">{{ latest.text|truncatewords:10 }}</p>
<div>
<p class="date">{{ latest.published_date }}</p>
<p class="showmore"><a href="">Show more</a></p>
</div>
</article>
{% endfor %}
</div>
</section>
<section id="posts">
{% for post in posts %}
<article class="post">
<header class="postheader">
<h4>{{ post.title }}</h4>
<p class="info">{{ post.category }}, {{ post.published_date }}</p>
</header>
<p class="bodyregular">{{ post.text|linebreaksbr }}</p>
<footer class="postfooter">
<p class="author">Author: {{ post.author }}</p>
<p class="showarticle"><a href="">Show article</a></p>
</footer>
</article>
{% endfor %}
</section>
def latest_posts(request):
latests = Post.objects.filter(published_date__lte=timezone.now()).reverse()[:3]
return render(request, 'blog/post_list.html', {'latests': latests})
def latest_posts(request):
latests = Post.objects.filter(published_date__lte=timezone.now()).reverse()[:3]
return render(request, 'blog/post_list.html', {'latest': latest})
def latest_posts(request):
latests = Post.objects.filter(published_date__lte=timezone.now()).reverse()[:3]
return render(request, 'blog/post_list.html', {'latests': latests})