Search code examples
pythondjangolistviewdjango-querysetposts

how to make a list of posts titles in django


I am creating a blog web app with django where i want to make a list which contains only titles of the posts. i wanna make two lists namely

  1. Latest posts
  2. All posts

In Latest posts , i wanna list out titles of the posts created recently.Means post created at last should be in first place of the list. simple

In All Posts , i want to list out titles of all posts in ascending order. i am not sure how to do it.

Here is my code goes.....

views.py

from django.shortcuts import render , redirect
from django.views.generic import TemplateView , ListView , DetailView
from .models import home_blog_model
from .forms import create_post

class home_view(ListView):
    model = home_blog_model
    template_name = "home.html"
    context_object_name = "posts"


def detail_view(request , pk):
    obj = home_blog_model.objects.get(id=pk)
    context = {"obj":obj}

    return render(request , "detail.html" , context)

def create_post_view(request):
    if request.method == "POST":
        form = create_post(request.POST)
        if form.is_valid():
            form.save()

            return redirect("/home/")

    else:
        form = create_post()
    return render(request , "create_post.html" , {"form":form})

home.html

{% extends "base.html" %}
{% load static %}
{% block body %}
    <img src="{% static 'hori.jpg' %}" style="margin-top: 50px;margin-left: 250px;width: 60%">



    <div class="row" style="margin-top: 40px;margin-left: 320px;margin-right: 20px">
        {% for post in posts %}
            <div class="col-sm-6 mb-4">
                <div class="container" style="width: 300px;box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);transition: 0.3s;width: 100%;padding: 0px;">



                    <div class="card" style="height: 200px;padding: 12px;" onclick="location.href='{% url 'detail' post.id %}'">
                        <h2>{{ post.title }}</h2>
                        <div class="card-body">{{ post.summary }}</div>
                    </div>
                </div>
            </div>
        {% endfor %}
    </div>

{% endblock %}

{% block head %}
<style>
    .card:hover { box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2);}
</style>
{% endblock %}

models.py

from django.db import models

class home_blog_model(models.Model):
    title = models.CharField(max_length=100)
    summary = models.CharField(max_length=300)
    content = models.TextField()
    date = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

urls.py

from django.urls import path
from . import views
from django.contrib.auth.views import LoginView , LogoutView
urlpatterns = [

    path("" , views.home_view.as_view() , name="blog-home"),
    path("posts/<int:pk>/" , views.detail_view , name="detail"),
    path("admin/login/" , LoginView.as_view(template_name="admin-login.html") , name="admin-login"),
    path("admin/logout/" , LogoutView.as_view() , name="admin-logout"),
    path("admin/post/create/" , views.create_post_view , name="create_post"),
]

thanks in advance.


Solution

  • You can use dictsortreversed for latest posts. For example:

    # top 5 posts
    {% for post in posts|dictsortreversed:"id"|slice:"5" %}
         {{ post.title }}
    {% endfor %}
    

    In this way you can have posts in ascending order (like the implementation of your code) and reversed order in same template without adding anything in view. slice was added for slicing the list for 5 objects.