gulic
gulic

Reputation: 123

Display latest post from models on homepage in django

I have 3 applications and I want to display the latest posts from them on homepage (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)

Other two (Recenzii and Lekcii) are mostly the same.

Analizi views.py:

def analizi(request):
    post = Analiza.objects.order_by('-published')[:5]
    return render_to_response( 'index.html', {'posts': post},)

But with this view I can see the results on http://websiteurl.com/analizi (and I know that's wrong).

How can I show the latest posts from all 3 applications on homepage?

Upvotes: 2

Views: 855

Answers (2)

George
George

Reputation: 169

An additional example that shows how to load the posts in the view.py of your page

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>

Upvotes: 0

Yossi
Yossi

Reputation: 12100

You should load the posts in the veiw.py of your homepage:

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())

Then in use them in you index.html.

Upvotes: 3

Related Questions