Getting Relative Import Error While Registering Models Django

Viewed 44

I was following the django documentation tutorial to make my first app, and then I reached the admin.py part and was trying to register my models, but then I got this error:

Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

My Folder Structure:

├───Poll
│   └───__pycache__
└───polls
    ├───migrations
    │   └───__pycache__
    └───__pycache__

Visual Representation:

enter image description here

My Code in admin.py:

from django.contrib import admin
from models import Question, Choice

admin.site.register(Question)
admin.site.register(Choice)

Settings.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'members.apps.MembersConfig',
]
2 Answers

I could see one problem i.e. import should be either from current location, using . or specify some app name.

Through current location:

from .models import Question, Choice

Through app name:

from some_app_name.models import Question, Choice

Figured it out after many frustrating hours. Basically in admin.py you register the model and instead of running the file, type py manage.py runserver.

Here's an example: Admin.py:

from django.contrib import admin
from .models import Person

admin.site.register(Person)

Instead of running the file separately, do this:

CMD:

cd yourproject
py manage.py runserver

And It works.

Related