每当我运行程序时,都会出现以下错误:
NameError at /table/
name 'models' is not defined
它说我的观点中第4行出现了错误。
这是我的views.py:
from django.shortcuts import render
def display(request):
return render(request, 'template.tmpl', {'obj': models.Book.objects.all()})
这是我的models.py:
from django.db import models
class Book(models.Model):
author = models.CharField(max_length = 20)
title = models.CharField(max_length = 40)
publication_year = models.IntegerField()
这是我的urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
# /table/
url(r'^$', views.display, name='display'),
]
有人可以告诉我出了什么问题吗?
答案 0 :(得分:4)
您在视图中引用models.Book
,但尚未导入models
。在views.py中,您需要执行from myapp import models
。或者您可以执行from myapp.models import Book
并在视图功能中将其更改为Book.objects.all()
。