Home > Blockchain >  Django: Why im getting NameError in shell if I have correct import in admin.py
Django: Why im getting NameError in shell if I have correct import in admin.py

Time:06-05

I don't really understand why i get NameError when i try run Post.objects.all() in shell.(by using django_extensions)

I made migrations and I see posts_post table on db(work fine) and i can do CRUD operations in running applicationon local server.

Below is my code and error message.

posts app

admin.py:

from django.contrib import admin
from .models import Post

admin.site.register(Post)

settings.py:

INSTALLED_APPS = [
    ...
    'django_extensions',
    'posts.apps.PostsConfig'
]

shell

Traceback (most recent call last)
Input In [1], in <cell line: 1>()
----> 1 Post.objects.all()
NameError: name 'Post' is not defined

CodePudding user response:

You have to import model first, so write it as following:

from some_app_name.models import Post
Post.objects.all()

And don't write from .models import Post as it requires appname.

Example: If the appname is posts so you should write:

from posts.models import Post
Post.objects.all()
  • Related