Joe Lin
Joe Lin

Reputation: 633

django templates help,upside down

I am trying to build my blog using Django 1.8 however I do not know how can I order the blogs. See the imageenter image description here

I want to display the 'earliest' at the bottom and the 'latest' at the top. Here is my

index.html

{% extends 'layouts/base.html' %}
{% block title %}
Homepage - {{ block.super }}
{% endblock title %}
{% block content %}
<center>
{% for blog in blogs %}
<h2><a href="{% url 'blog_detail' slug=blog.slug %}">
{{ blog.name }}
</a></h2>
<p>{{ blog.description }}</p>
{% endfor %}
</center>
{% endblock content %}

models.py

# -*- coding: utf-8 -*-
from django.db import models
from django.utils import timezone


class blog(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField()
    slug = models.SlugField(unique=True)
    date_time = models.DateTimeField(auto_now_add = True)

    def __unicode__(self):
        return self.name



def get_image_path(instance, filename):
    return '/'.join(['blog_images', instance.bupimg.slug, filename])

class Upload(models.Model):
    bupimg = models.ForeignKey(blog, related_name="uploads")
    image = models.ImageField(upload_to=get_image_path)

views.py

from django.shortcuts import render
from blogging.models import *


def index(request):
    blogs = blog.objects.all()
    return render(request, 'index.html', {
        'blogs':blogs,
    })

def blog_detail(request, slug):
    article = blog.objects.get(slug=slug)
    uploads = article.uploads.all()
    return render(request, 'blogs/blog_detail.html', {
        'article': article,
        'uploads': uploads,
    })

How can I move the blog title 'earliest' to the downside ,'latest' on top side? I need let the latest blog shows on the top.

Upvotes: 1

Views: 182

Answers (1)

Selcuk
Selcuk

Reputation: 59315

You are not sorting the blogs, they come in a random order. Try changing the line

blogs = blog.objects.all()

to

blogs = blog.objects.order_by('-date_time')

The minus (-) denotes descending sort, ie. from the latest to the oldest.

Upvotes: 5

Related Questions