2

I am trying to query data from database using Python shell. settings.py includes:


import django
django.setup()

...

INSTALLED_APPS = [
    'django.contrib.contenttypes',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'products.apps.ProductsConfig',
    'users.apps.UsersConfig',
    'crispy_forms',
]

When i open Python shell i do:

> from django.conf import settings
> settings.configure()

Then I try to import models:

> from products.models import Product

However, Python returns:

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

I tried adding django.setup() call in settings and also moving this statement after INSTALLED_APPS.

EDIT: With django.setup() I get the following error when I try to run command runserver:

django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.

Matej J
  • 615
  • 1
  • 9
  • 33
  • There is a special command for that https://docs.djangoproject.com/en/3.0/ref/django-admin/#shell . No need to do any extra setup. – Davit Tovmasyan Apr 27 '20 at 18:56

1 Answers1

2

As you noticed, django hasn't been properly initialized and so you are getting this message.

As @davit-tovmasyan mentioned, there is a built in manage.py command to open a django shell in the correct context:

./manage.py shell

Additionally, if you install django-extensions there is a very helpful command which imports all your models, plus common imports:

$ ./manage.py shell_plus

# Shell Plus Model Imports
from django.contrib.admin.models import LogEntry
from project.my_app.models import Model1, Model2
# ...etc, for all django and project apps
# Shell Plus Django Imports
from django.core.cache import cache
from django.conf import settings
# ...
>>> type your python here

If you want to run your own script, for example in temp.py, then you can copy the manage.py code into a new file and run it directly:

import os
import django

# these must be before any other imports of django app code/models
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
django.setup() 

from my_app.models import Product
print(Product.objects.all())

# at the command line:
$> chmod +x temp.py
$> ./tmp.py

Also, with django-extensions run_script, is the scripts folder where you can add simple python scripts with a run() method.

Andrew
  • 8,322
  • 2
  • 47
  • 70