Search code examples
pythondjangodjango-viewsdjango-templates

Entries not showing on page


Cant seem to figure out why my entries from my database are not appearing on my page but my topics name on the entry page is

I'm trying to show show entries from my database on a page, the link to the page works and the Topic name from the database appearing but the entries from the database is not.

views.py

from django.shortcuts import render

from .models import Topic

# Create your views here.
def index(request):
    """The home page for learning log."""
    return render(request, 'learning_logs/index.html')

def topics(request):
    """Show all topics"""
    topics = Topic.objects.order_by('date_added')
    context = {'topics': topics}
    return render(request, 'learning_logs/topics.html', context)

def topic(request, topic_id):
    """Show  a single topic and all its entries"""
    topic = Topic.objects.get(id=topic_id)
    entries = topic.entry_set.order_by('-date_added')
    context = {'topic': topic, 'entries': entries}
    return render(request, 'learning_logs/topic.html', context)

topic.html

{% extends 'learning_logs/base.html' %}

{% block content %}

    <p>Topic: {{ topic.text }}</p>

    <p>Entries:</p>
    <ul>
        {% for topic in topics %}
            <li>
                <p>{{ entry.date_added|date:'M d, Y H:i' }}</p>
                <p>{{ entry.text|linebreaks }}</p>
            </li>
        {% empty %}
            <li>There are no entries for this topic yet.</li>
        {% endfor %}
    </ul>

    {% endblock content %}

models.py

from django.db import models

# Create your models here.
class Topic(models.Model):
    """A topic the user is learning about."""
    text = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.text
    
class Entry(models.Model):
    """Something specific learned about a topic"""
    topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
    text = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = 'entries'

    def __str__(self):
        """Return a simple string representation of the entry."""
        return f"{self.text[:50]}..."

output


Solution

  • Since i don't have enought reputation to only comment, Just change {% for topic in topics %} to {% for entry in entries %} in your learning_logs/base.html template file