RuntimeError: Model class polls38.polls.models.Question doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

254 views
Skip to first unread message

Ennio Santos

unread,
Dec 3, 2020, 8:40:25 PM12/3/20
to Django users
I developed some small web app using Django, but I had not used virtual env up to the moment.

I am facing the erro above, I can imagine that is related to some kind of path definition  that is not properly defined, but have no idea where to begin.

My Env

windows 10 home
Currently using CONDA, version 4.9.2, installed on my "C" driver. 

# conda environments:
#
base                     C:\ProgramData\Anaconda3
pranos39                 C:\ProgramData\Anaconda3\envs\pranos39
agen37                   C:\Users\ennio\.conda\envs\agen37
agen39                   C:\Users\ennio\.conda\envs\agen39
baseold                  C:\Users\ennio\.conda\envs\baseold
python38                 C:\Users\ennio\.conda\envs\python38
                            *  d:\conda_env\py38 (this is the one I activate)

And the editor is vscode 1.51.1 version. using pylint, and it is pointing to the python env above.







I have the driver "D" where is the conda env being used. And also, where is the source code.

D:\Linguagem\mooc\code\polls38





Tutorial being used

since it is the first time using the virtual env to build a django app, I decide to use the tutorial available to test:

Using the exemplo, as it is.


 (d:\conda_env\py38) D:\Linguagem\mooc\code\polls38>conda list

# packages in environment at d:\conda_env\py38:
#
# Name                    Version                   Build  Channel

asgiref                   3.3.1              pyhd3eb1b0_0
astroid                   2.4.2                    py38_0
ca-certificates           2020.10.14                    0
certifi                   2020.11.8        py38haa95532_0
colorama                  0.4.4                      py_0
django                    3.1.3              pyhd3eb1b0_0
isort                     5.6.4                      py_0
krb5                      1.17.1               hc04afaa_0
lazy-object-proxy         1.4.3            py38he774522_0
libpq                     12.2                 h3235a2c_0
mccabe                    0.6.1                    py38_1
openssl                   1.1.1h               he774522_0
pip                       20.3             py38haa95532_0
psycopg2                  2.8.5            py38h7a1dbc1_0
pylint                    2.6.0                    py38_0
python                    3.8.5                h5fd99cc_1
pytz                      2020.4             pyhd3eb1b0_0
setuptools                50.3.1           py38haa95532_1
six                       1.15.0           py38haa95532_0
sqlite                    3.33.0               h2a8f88b_0
sqlparse                  0.4.1                      py_0
tk                        8.6.10               he774522_0
toml                      0.10.1                     py_0
vc                        14.1                 h0510ff6_4
vs2015_runtime            14.16.27012          hf0eaf9b_3
wheel                     0.35.1             pyhd3eb1b0_0
wincertstore              0.2                      py38_0
wrapt                     1.11.2           py38he774522_0
zlib                      1.2.11               h62dcd97_4

The settings.py file


from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
print(BASE_DIR)

# Quick-start development settings - unsuitable for production

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '********'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'polls38.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'polls38.wsgi.application'


# Database

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization

LANGUAGE_CODE = 'pt-br'

TIME_ZONE = 'America/Sao_Paulo'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)

STATIC_URL = '/static/'


To create de app "polls" I had to use the command:

django-admin startapp polls  polls38/polls (firstly I created the folder).

I was facing an error, when running "python manage.py runserver".
ERROR: module no found "polls".
I solved the problem, by adding at the manage.py the path to the app, as bellow (i do not believe that its the best solution)


def main():
    """Run administrative tasks."""
    sys.path.append('D:/linguagem/mooc/code/polls38/polls38')
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'polls38.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)

I was able to run the first and second part of the tutorial.
In the third part, after improving the polls/views, another problem showed-up.



And if I try to run, the follwing error occurs:

when I issue the command "python manage.py runserver"

(d:\conda_env\py38) D:\Linguagem\mooc\code\polls38>python manage.py runserver
D:\Linguagem\mooc\code\polls38
D:\Linguagem\mooc\code\polls38
Watching for file changes with StatReloader
Performing system checks...

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "d:\conda_env\py38\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "d:\conda_env\py38\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "d:\conda_env\py38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "d:\conda_env\py38\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run
    self.check(display_num_errors=True)
  File "d:\conda_env\py38\lib\site-packages\django\core\management\base.py", line 392, in check
    all_issues = checks.run_checks(
  File "d:\conda_env\py38\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "d:\conda_env\py38\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
    return check_resolver(resolver)
  File "d:\conda_env\py38\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
    return check_method()
  File "d:\conda_env\py38\lib\site-packages\django\urls\resolvers.py", line 408, in check
    for pattern in self.url_patterns:
  File "d:\conda_env\py38\lib\site-packages\django\utils\functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "d:\conda_env\py38\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "d:\conda_env\py38\lib\site-packages\django\utils\functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "d:\conda_env\py38\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module
    return import_module(self.urlconf_name)
  File "d:\conda_env\py38\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "D:\Linguagem\mooc\code\polls38\polls38\urls.py", line 20, in <module>
    path('', include('polls38.polls.urls')),
  File "d:\conda_env\py38\lib\site-packages\django\urls\conf.py", line 34, in include
    urlconf_module = import_module(urlconf_module)
  File "d:\conda_env\py38\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "D:\Linguagem\mooc\code\polls38\polls38\polls\urls.py", line 3, in <module>
    from . import views
  File "D:\Linguagem\mooc\code\polls38\polls38\polls\views.py", line 7, in <module>
    from .models import Question
  File "D:\Linguagem\mooc\code\polls38\polls38\polls\models.py", line 6, in <module>
    class Question(models.Model):
  File "d:\conda_env\py38\lib\site-packages\django\db\models\base.py", line 113, in __new__
    raise RuntimeError(
RuntimeError: Model class polls38.polls.models.Question doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.


Any help on how to fix?

tks a lot!!




Ryan Gedwill

unread,
Dec 4, 2020, 1:33:41 AM12/4/20
to django...@googlegroups.com
you at least need to add 'polls' to your INSTALLED_APPS in settings.py. You should also remove the line you put in manage.py - that file should rarely be touched at all.

This is not a system path problem



--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/54c2664d-315b-46c4-baae-c7eddab7c19cn%40googlegroups.com.

Ryan Gedwill

unread,
Dec 4, 2020, 1:37:22 AM12/4/20
to django...@googlegroups.com
you may also need to change polls/apps.py to have a config class

Ennio Santos

unread,
Dec 4, 2020, 9:40:10 AM12/4/20
to Django users
Ryang, tks for your answer.

Removing  from manage.py, as your suggestion:

apps.py is already configured as is in tutorial.



the settings.py is already configured as in tutorial.



if I run python manage.py runserver

this is the result: module not found.

(d:\conda_env\py38) D:\Linguagem\mooc\code\polls38>python manage.py runserver
D:\Linguagem\mooc\code\polls38
D:\Linguagem\mooc\code\polls38
Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "d:\conda_env\py38\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "d:\conda_env\py38\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "d:\conda_env\py38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "d:\conda_env\py38\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run
    autoreload.raise_last_exception()
  File "d:\conda_env\py38\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception
    raise _exception[1]
  File "d:\conda_env\py38\lib\site-packages\django\core\management\__init__.py", line 357, in execute
    autoreload.check_errors(django.setup)()
  File "d:\conda_env\py38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "d:\conda_env\py38\lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "d:\conda_env\py38\lib\site-packages\django\apps\registry.py", line 91, in populate
    app_config = AppConfig.create(entry)
  File "d:\conda_env\py38\lib\site-packages\django\apps\config.py", line 116, in create
    mod = import_module(mod_path)
  File "d:\conda_env\py38\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'polls'
Traceback (most recent call last):
  File "manage.py", line 23, in <module>
    main()
  File "manage.py", line 19, in main
    execute_from_command_line(sys.argv)
  File "d:\conda_env\py38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "d:\conda_env\py38\lib\site-packages\django\core\management\__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "d:\conda_env\py38\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv
    self.execute(*args, **cmd_options)
  File "d:\conda_env\py38\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute
    super().execute(*args, **options)
  File "d:\conda_env\py38\lib\site-packages\django\core\management\base.py", line 371, in execute
    output = self.handle(*args, **options)
  File "d:\conda_env\py38\lib\site-packages\django\core\management\commands\runserver.py", line 96, in handle
    self.run(**options)
  File "d:\conda_env\py38\lib\site-packages\django\core\management\commands\runserver.py", line 103, in run
    autoreload.run_with_reloader(self.inner_run, **options)
  File "d:\conda_env\py38\lib\site-packages\django\utils\autoreload.py", line 614, in run_with_reloader
    start_django(reloader, main_func, *args, **kwargs)
  File "d:\conda_env\py38\lib\site-packages\django\utils\autoreload.py", line 599, in start_django
    reloader.run(django_main_thread)
  File "d:\conda_env\py38\lib\site-packages\django\utils\autoreload.py", line 314, in run
    self.run_loop()
  File "d:\conda_env\py38\lib\site-packages\django\utils\autoreload.py", line 320, in run_loop
    next(ticker)
  File "d:\conda_env\py38\lib\site-packages\django\utils\autoreload.py", line 360, in tick
    for filepath, mtime in self.snapshot_files():
  File "d:\conda_env\py38\lib\site-packages\django\utils\autoreload.py", line 376, in snapshot_files
    for file in self.watched_files():
  File "d:\conda_env\py38\lib\site-packages\django\utils\autoreload.py", line 274, in watched_files
    yield from iter_all_python_module_files()
  File "d:\conda_env\py38\lib\site-packages\django\utils\autoreload.py", line 105, in iter_all_python_module_files
    return iter_modules_and_files(modules, frozenset(_error_files))
  File "d:\conda_env\py38\lib\site-packages\django\utils\autoreload.py", line 141, in iter_modules_and_files
    resolved_path = path.resolve(strict=True).absolute()
  File "d:\conda_env\py38\lib\pathlib.py", line 1177, in resolve
    s = self._flavour.resolve(self, strict=strict)
  File "d:\conda_env\py38\lib\pathlib.py", line 200, in resolve
    return self._ext_to_normal(_getfinalpathname(s))
OSError: [WinError 123] A sintaxe do nome do arquivo, do nome do diretório ou do rótulo do volume está incorreta: '<frozen importlib._bootstrap>'

If I add polls to the INSTALLED_APP as in old version.



and issue the command: python manage.py runserver

I still have the save problem.

(d:\conda_env\py38) D:\Linguagem\mooc\code\polls38>python manage.py runserver
D:\Linguagem\mooc\code\polls38
D:\Linguagem\mooc\code\polls38
Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "d:\conda_env\py38\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "d:\conda_env\py38\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "d:\conda_env\py38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "d:\conda_env\py38\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run
    autoreload.raise_last_exception()
  File "d:\conda_env\py38\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception
    raise _exception[1]
  File "d:\conda_env\py38\lib\site-packages\django\core\management\__init__.py", line 357, in execute
    autoreload.check_errors(django.setup)()
  File "d:\conda_env\py38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "d:\conda_env\py38\lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "d:\conda_env\py38\lib\site-packages\django\apps\registry.py", line 91, in populate
    app_config = AppConfig.create(entry)
  File "d:\conda_env\py38\lib\site-packages\django\apps\config.py", line 116, in create
    mod = import_module(mod_path)
  File "d:\conda_env\py38\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'polls'
Traceback (most recent call last):
  File "manage.py", line 23, in <module>
    main()
  File "manage.py", line 19, in main
    execute_from_command_line(sys.argv)
  File "d:\conda_env\py38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "d:\conda_env\py38\lib\site-packages\django\core\management\__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "d:\conda_env\py38\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv
    self.execute(*args, **cmd_options)
  File "d:\conda_env\py38\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute
    super().execute(*args, **options)
  File "d:\conda_env\py38\lib\site-packages\django\core\management\base.py", line 371, in execute
    output = self.handle(*args, **options)
  File "d:\conda_env\py38\lib\site-packages\django\core\management\commands\runserver.py", line 96, in handle
    self.run(**options)
  File "d:\conda_env\py38\lib\site-packages\django\core\management\commands\runserver.py", line 103, in run
    autoreload.run_with_reloader(self.inner_run, **options)
  File "d:\conda_env\py38\lib\site-packages\django\utils\autoreload.py", line 614, in run_with_reloader
    start_django(reloader, main_func, *args, **kwargs)
  File "d:\conda_env\py38\lib\site-packages\django\utils\autoreload.py", line 599, in start_django
    reloader.run(django_main_thread)
  File "d:\conda_env\py38\lib\site-packages\django\utils\autoreload.py", line 314, in run
    self.run_loop()
  File "d:\conda_env\py38\lib\site-packages\django\utils\autoreload.py", line 320, in run_loop
    next(ticker)
  File "d:\conda_env\py38\lib\site-packages\django\utils\autoreload.py", line 360, in tick
    for filepath, mtime in self.snapshot_files():
  File "d:\conda_env\py38\lib\site-packages\django\utils\autoreload.py", line 376, in snapshot_files
    for file in self.watched_files():
  File "d:\conda_env\py38\lib\site-packages\django\utils\autoreload.py", line 274, in watched_files
    yield from iter_all_python_module_files()
  File "d:\conda_env\py38\lib\site-packages\django\utils\autoreload.py", line 105, in iter_all_python_module_files
    return iter_modules_and_files(modules, frozenset(_error_files))
  File "d:\conda_env\py38\lib\site-packages\django\utils\autoreload.py", line 141, in iter_modules_and_files
    resolved_path = path.resolve(strict=True).absolute()
  File "d:\conda_env\py38\lib\pathlib.py", line 1177, in resolve
    s = self._flavour.resolve(self, strict=strict)
  File "d:\conda_env\py38\lib\pathlib.py", line 200, in resolve
    return self._ext_to_normal(_getfinalpathname(s))
OSError: [WinError 123] A sintaxe do nome do arquivo, do nome do diretório ou do rótulo do volume está incorreta: '<frozen importlib._bootstrap>'

the message in portuguese is: "The syntax of the file name, directory name, or volume label is incorrect:" do it means something for you?


If you have any other suggestion, I am open to hear and test.

Ennio Santos

unread,
Dec 4, 2020, 12:20:31 PM12/4/20
to Django users
I found the error.

In the tutorial the way we specify the path

what I had to do different


I was required to add the project folder. But the question: What is missing in the configuration or in the installation process? Or the way the tutorial is presented is wrong?

Reply all
Reply to author
Forward
0 new messages