I am trying to apply a for loop to the following html (in a Django project) such that the 'Name' and the 'Comments' field are caused to repeat on the html view.
When I insert the templating code, that is:
{% for c in comments %}
{% endfor %}
on either side of the content i want to repeat, it simply makes the name and comments disappear altogether and does not have the desired result.
The relevant parts of the file are below:
index.html (the main html page)
{% load static %}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="{% static 'guestbook/styles.css' %}">
</head>
<body>
<h1>The world's guestbook</h1>
<p><a href="{% url 'sign' %}">Sign </a>the guestbook</p>
{% for c in comments %}
<h2>Name</h2>
<p>This the message that the user leaves.</p>
{% endfor %}
</body>
</html>
views.py (in the guestbook app)
from django.shortcuts import render
from .models import Comment
# Create your views here.
def index(request):
comments = Comment.objects.order_by('-date_added')
context ={'comments': comments}
#name=Name.objects.order_by('-date_added')
return render(request,'guestbook/index.html')
def sign(request):
return render(request,'guestbook/sign.html')
models.py file
from django.db import models
from django.utils import timezone
# Create your models here.
class Comment(models.Model):
name=models.CharField(max_length=20)
comment=models.TextField()
date_added=models.DateTimeField(default=timezone.now)
def __str__(self):
return self.name
I am working off a tutorial in which this is the recommended code and the desired result is as expected - I notice my html template does not have div tags and wonder if that could be an issue? If so, how can it be resolved?