Loading model items into html

Hey, I’m new to Django and I’m trying to build my first app “solar” ( using: Writing your first Django app, part 3, as an example)

I got a simple model called “Planet” with an attribute: planet_name. I added some planets to the model “Earth”, “Mars”, etc, which I can modify as admin. Everything works so far.

I like to get the planet names from the model and show them on a HTML page. In the solar/views.py I made a function index(request), which should make a list of all the planets. The HTML page should get the list of planets, but in my case it runs an exception “No planets are available” , which means I can’t get the list of planets.

Can somebody please explain what I’m doing wrong, and point out how I can solve a problem in Django without an error to look up?


from django.contrib import admin
from django.urls import include, path

urlpatterns = [
	path('solar/', include('solar.urls')),
	path('admin/', admin.site.urls),


from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader

from .models import Planet

def index(request):
    latest_planet_list = Planet.objects.all()
    template = loader.get_template('solar/index.html')
    context = {
        'latest_planet_list': latest_planet_list,
    return HttpResponse(template.render(context, request))


{% if latest_question_list %}
    {% for planet in latest_planet_list %}
        <li><a href="/solar/{{ planet.id }}/">{{ planet.planet_name }}</a></li>
    {% endfor %}
{% else %}
    <p>No planets are available.</p>
{% endif %}


import datetime

from django.db import models
from django.utils import timezone

class Planet(models.Model):
    planet_name = models.CharField(max_length=15)
    planet_size = models.CharField(max_length=15)

Hi! I think the issue lies in the if statement, which asks for variable that is not defined on the context.

Btw you can simplify your template rendering with the render shortcut. In your case it would look like this:

def index(request):
    latest_planet_list = Planet.objects.all()
    context = {
        'latest_planet_list': latest_planet_list,
    return render('solar/index.html', context)
1 Like

omg, if feel so stupid. thank you for finding my mistake and for the extra advice.