{% extends 'learning_logs/base.html' %}
{% block content %}
<p>Topic:{{ topic }}</p>
<p>Entries:</p>
<ul>
{% for entry in entries %}
<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 %}
from django.shortcuts import render
from .models import Topic
# 在这里创建视图
def index(request):
"""学习笔记主页"""
return render(request,'learning_logs/index.html')
def topics(request):
"""显示所有主题"""
topics = Topic.objects.order_by('date_added')
context = {'topics':topics}
return render(request,'learning_logs/topics.html',context)
def topic(request,topic_id):
"""显示主题对于的条目"""
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)
from django.db import models
#在这里创建模型
class Topic(models.Model):
"""用户学习的主题"""
text = models.CharField(max_length=200)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
"""返回模型字符串的表示"""
return self.text
class Entry(models.Model):
topic = models.ForeignKey(Topic,on_delete=models.CASCADE)
text = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
class Mate:
verbose_name_plural = 'entries'
def __str__(self):
if (len(self.text)) > 50:
return f"{self.text[:50]}..."
else:
return self.text
from django.urls import path,re_path
from . import views
app_name = 'learning_logs'
urlpatterns=[
# 主页面
path('',views.index,name='index'),
#显示所有主题的页面
path('topics/',views.topics,name='topics'),
#特定主题的详情页面
path('topics/<int:topic_id>/',views.topic,name='topic')
]
Django Version: 4.0.2
Exception Type: OperationalError
Exception Value: no such column: learning_logs_entry.date_added
no such column是没有这个列,应该是你数据读取方式错了,在视图函数确认一下有没有entry.date_added这个数据
topic = Topic.objects.get(id=topic_id)
entries = topic.entry_set.order_by('-date_added')
我建议你打印一下这两个变量,看看取值是不是符合你得要求
应该是你之前修改了entry里的东西,但没有迁移到数据库中
请问你这个问题解决了吗,我遇到了类似的问题,我为每个topic都添加了entry,但是页面仍然显示There are no entries for this topic yet