我已验证“书籍”表中有条目,但是由于似乎无法查明原因,我的模板未显示它们。
型号:
class Book(models.Model):
bookTitle = models.CharField(max_length = 100)
bookURL = models.SlugField()
bookContent = models.TextField()
bookAuthor = models.ForeignKey(User, on_delete = models.CASCADE, related_name = 'books')
creationDate = models.DateTimeField()
模板:
{% extends 'base.html' %}
{% block content %}
{% for p in books %}
<div class="post-wrapper col-lg-8 card" style="border: 1px solid black; margin: 20 auto;">
<div class="card-body">
<div class="card-title">{{ p.bookTitle }}</div>
<div class="card-body">
{{ p.bookContent }}
</div>
<em style="margin-left: 10px;"><small>written by {{ p.bookAuthor }} at {{ p.creationDate }}</small></em>
</div>
</div>
{% endfor %}
{% endblock %}
查看:
from django.shortcuts import render
from django.http import HttpResponse
from .models import Book
from django.utils import timezone
# Create your views here.
def viewAll(request):
books = Book.objects.all()
return render(request, 'viewAll.html', {})
答案 0 :(得分:3)
您没有将任何数据传递到视图上下文-您需要在上下文字典(第三个参数)中传递books
:
def viewAll(request):
books = Book.objects.all()
return render(request, 'viewAll.html', {'books': books}) # <--- this is currently empty