Tuesday, April 22, 2025

Django To-Do - Listing Posts

You are advised to check corresponding YouTube video at the end of this article.

The view function is called index, and it takes a request object as its argument. The render function from Django's shortcuts module is used to generate an HTTP response by rendering a template with a context.

The view function starts by calling the all() method on the Posts model, which returns a queryset containing all instances of the Posts model in the database. The [:10] slice syntax is used to limit the queryset to the first 10 items, so that only the 10 most recent posts will be displayed.

The resulting queryset is stored in the all_posts variable, which is then included in a dictionary called context.

Finally, the render function is called with three arguments: the request object, the name of the template to render ('index.html'), and the context dictionary containing the queryset of posts. This generates an HTTP response containing the rendered template, which will display the 10 most recent posts on the page.

To list posts on homepage we need to fix views.py first:


from django.shortcuts import render
from .models import Posts

def index(request):
    all_posts = Posts.objects.all()[:10]
    context = {'all_posts' : all_posts}
    return render (request, 'index.html', context)


"""
def index(request):
    return render(request, 'index.html', {})
"""

With for loop we will extract posts for db and flush them in index.html:


<h1>All Posts: </h1>

{% for post in all_posts %}
  <ul>
    <li>{{ post.id }} - {{ post.title }} - {{ post.text }}</li>
  </ul>

{% endfor %}

In next tutorial we will work with base template, to prepare situation for multiple custom html pages/templates that will deal with posts from db in different ways.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...