Andrew Quoc-Anh Ho Andrew Quoc-Anh Ho - 2 months ago 10
Python Question

Why am I getting the following error: NameError: name 'models' is not defined

Whenever I run the program, I get the following error:

NameError at /table/
name 'models' is not defined


It says that there's an error on line 4 in my views.

Here is my views.py:

from django.shortcuts import render

def display(request):
return render(request, 'template.tmpl', {'obj': models.Book.objects.all()})


Here is my 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()


Here is my urls.py:

from django.conf.urls import url
from . import views

urlpatterns = [
# /table/
url(r'^$', views.display, name='display'),
]


Can somebody please tell me what is wrong?

Answer

You are referencing models.Book in your view, but you have not imported models. In your views.py you need to do from myapp import models. Or you can do from myapp.models import Book and change it in your view function to just Book.objects.all().

Comments