我有3个应用程序,我想在主页(index.html)上显示它们的最新帖子。
Analizi models.py:
class Analiza(models.Model):
published = models.DateTimeField(default = datetime.now)
title = models.CharField(max_length = 500)
avtor = models.CharField(max_length = 200)
analiza_text = models.TextField(blank = True, null = True)
approved = models.BooleanField(default=False)
class Meta:
permissions = (
("can_approve_post", "Can approve post"),
)
def _unicode_(self):
return self.title
def get_absolute_url(self):
return "/%s/%s/%s/" % (self.published.year, self.published.month, self.slug)
其他两个(Recenzii和Lekcii)大致相同。
Analizi views.py:
def analizi(request):
post = Analiza.objects.order_by('-published')[:5]
return render_to_response( 'index.html', {'posts': post},)
但是通过这种观点,我可以在http://websiteurl.com/analizi上看到结果(我知道这是错的)。
如何在主页上显示所有3个应用程序的最新帖子?
答案 0 :(得分:3)
您应该在主页的veiw.py
中加载帖子:
def index(request):
posts = Analiza.objects.order_by('-published')[:5]
lektcii = Lektcii.objects.order_by('-published')[:5]
recenzii = Recenzii.objects.order_by('-published')[:5]
data = {'posts': posts, 'lektzii': lektzii, 'recenzii': recenzii}
render_to_response('index.html', data, context_instance=RequestContext())
然后在你index.html
中使用它们。
答案 1 :(得分:0)
另一个示例,说明如何在页面的view.py中加载帖子
views.py
def example(request):
post = Post.objects.first()
template = 'data/example.html'
context = {'post': post}
return render(request, template, context)
<强> example.html的强>
{% if post.image %}
<img class="img-responsive" src="{{ post.image.url }}">
{% endif %}
<h1><a href="{{post.get_absolute_url}}"> {{post.title}}</a></h1>
<p>by {{ post.author }} <span class="glyphicon glyphicon-time"></span> Posted on {{ post.published }}</p>
<p class="lead">{{post.content|truncatewords:100|linebreaks}}</p>