2

我有 3 个应用程序,我想在主页 (index.html) 上显示它们的最新帖子。

分析模型.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 个应用程序的最新帖子?

4

2 回答 2

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

于 2013-05-27T06:17:13.623 回答
0

另一个示例显示如何在页面的 view.py 中加载帖子

视图.py

def example(request):
        post = Post.objects.first()
        template = 'data/example.html'
        context = {'post': post}
        return render(request, template, context)

例子.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>
于 2017-03-28T08:05:43.063 回答