Django says - No module named 'blog'

2020-04-06 08:49发布

问题:

I am getting "ModuleNotFoundError: No module named 'blog'" error when add my blog app to the INSTALLED_APPS section of settings.py. I have determined that it has something to do with the way I have added the "blog" app under INSTALLED_APPS. When I remove the 'blog' reference from INSTALLED_APPS error goes away. It looks like that Django is unable to find directory for my blog app?

I have done one thing differently and that is use:

python manage.py startapp blog /myproject

Difference here is specifying the /myproject directory and not using:

python manage.py startapp blog

Which will place it under root directory myproject. I wanted to avoid adding app directory in the root folder so i stay more organized. But it looks like Django does not like this or i am not referencing this correctly in the INSTALLED_APPS section?

My project directory is as following:

myproject/
├── myproject
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-36.pyc
│   │   ├── settings.cpython-36.pyc
│   │   ├── urls.cpython-36.pyc
│   │   └── wsgi.cpython-36.pyc
│   ├── blog
│   │   ├── __init__.py
│   │   ├── admin.py
│   │   ├── apps.py
│   │   ├── migrations
│   │   │   └── __init__.py
│   │   ├── models.py
│   │   ├── tests.py
│   │   └── views.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── db.sqlite3
└── manage.py

Inside my settings.py I have setup my app blog:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
]

回答1:

Django needs to be able to import your application, usually this means including the full path relative to the root directory 'myproject.blog'.

You could add <full_path_to_your_project>/myproject/myproject to PYTHONPATH so that you can import blog, but I would not recommend it



回答2:

Directory structure is unusual. More usual and the one that matches your app being named blog would be

myproject/
├── myproject
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-36.pyc
│   │   ├── settings.cpython-36.pyc
│   │   ├── urls.cpython-36.pyc
│   │   └── wsgi.cpython-36.pyc
├── blog
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── db.sqlite3
└── manage.py


回答3:

I usually add the config path to installed apps to avoid this problem. So installed apps would look like this:

NSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog,apps.BlogConfig',