Naveed naseer
Naveed naseer

Reputation: 85

my articles shows up oldest first but i want it to show new one first like date wise new one should appear on top

hi i want to show my articles latest article should appear first i used class Meta in models but its not working it does not show any error but it it shows old articles on top. if anyone can please help that would be very helpfull

models.py

from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone


class Article(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField()
    body = models.TextField()
    date = models.DateTimeField(default=timezone.now)
    thumb = models.ImageField(default='default.png', blank=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE, default=None)

    class Meta:
        ordering = ['-date']

    def __str__(self):
        return self.title

    def snippet(self):
        return self.body[:100]+'...'

views.py

from django.http import HttpResponse
from django.shortcuts import render, redirect
from .models import Article
from django.contrib.auth.decorators import login_required
from . import forms


def article_list(request):
    articles = Article.objects.all().order_by('date')
    return render(request, 'articles/article_list.html', {'articles': articles})


def article_detail(request, slug):
    # return HttpResponse(slug)
    article = Article.objects.get(slug=slug)
    return render(request, 'articles/article_detail.html', {'article': article})


@login_required(login_url="/accounts/login/")
def article_create(request):
    if request.method == 'POST':
        form = forms.CreateArticle(request.POST, request.FILES)
        if form.is_valid():
            # save article to db
            instance = form.save(commit=False)
            instance.author = request.user
            instance.save()
            return redirect('articles:list')
    else:
        form = forms.CreateArticle()
    return render(request, 'articles/article_create.html', {'form': form})

Upvotes: 0

Views: 25

Answers (1)

Andee
Andee

Reputation: 793

In your article_list view you are ordering by date ascending (oldest first) which will override your model Meta. Either change that to -date or just remove the order_by to fall back to the Meta ordering.

Upvotes: 1

Related Questions