Search code examples
pythondjangodatabasemodel-view-controllermodel

Django "NameError: name 'Album' not defined"


I am trying to run see and manipulate a simple django database but the error from the Django Shell is saying one of my models isn't defined.

Most of the questions with errors similar to mine are due to people referencing a model before declaring it. However, I'm not referencing any other model in Album.

models.py

from __future__ import unicode_literals

from django.db import models


class Album(models.Model):
    artist = models.CharField(max_length=250)
    title = models.CharField(max_length=500)
    genre = models.CharField(max_length=100)
    logo = models.CharField(max_length=1000)


class Song(models.Model):
    album = models.ForeignKey(Album, on_delete=models.CASCADE)
    file_type = models.CharField(max_length=10)
    title = models.CharField(max_length=250)

The error I am getting: NameError: name 'Album' is not defined

Any idea what could the the cause of this error?

For reference, I'm following thenewboston's django tutorial here.


Solution

  • When you open your shell, it is just a python shell without anything from your app imported.

    You should import your models first:

    from your_app_name.models import Album
    

    If you don't want to import your models every time, use django-extensions which will load them for you. Use shell_plus command:

    python manage.py shell_plus
    

    Hope it helps