Andrew Quoc-Anh Ho Andrew Quoc-Anh Ho - 1 year ago 85
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

from django.shortcuts import render

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

Here is my

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

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 Source

You are referencing models.Book in your view, but you have not imported models. In your 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().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download