Tuesday, April 22, 2025

Django To-Do - Post Details

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

If we need to see post details on index.html, we need to fix it.

How? Well, every link needs to point to dedicated entry in database, which means, we must use IDs of posts:


{% extends 'base.html' %}
<h1>All Posts: </h1>

{% block listing %}

{% for post in all_posts %}
  <ul>
    <li><a href="details/{{ post.id }}">{{ post.title }} - {{ post.text }}</a></li>
  </ul>

{% endfor %}
{% endblock %}

To get post IDs as part of linking system, views.py must be changed:


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 details(request, id):
    one = Posts.objects.get(id=id)
    context = {'one' : one}
    return render (request, 'details.html', context)

Local urls.py for todo app must be changed too:


from django.urls import path
from .import views

urlpatterns = [
    path('', views.index, name='index'),
    path('details/<int:id>', views.details, name='details'),
]

It's time to create details.html page in templates directory:


{% extends 'base.html' %}

{% block details %}
<ul>
  <li>{{ one.id }}</li>
  <li>{{ one.title }}</li>
  <li>{{ one.text }}</li>
  <li>{{ one.created }}</li>
</ul>

{% endblock %}

Our base template (base.html) must hold block for details now:


{% include 'parts/header.html ' %}

{% block listing  %}
{% endblock %}

{% block details  %}
{% endblock %}

{% include 'parts/footer.html ' %}

Now you have index of posts on site homepage (index.html), that will lead visitors to dedicated details.html page for every post.

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 .  ...