PyGuide

Learn Python with practical tutorials and code examples

Python Import Module Not Found Error Solutions Django Flask Q&A

Python import module not found errors in Django and Flask applications can derail web development projects. This Q&A guide addresses the most common import issues specific to these popular web frameworks and provides practical solutions.

Q1: Django app module not found despite proper structure #

Problem: Getting ModuleNotFoundError when importing Django apps or models, even with correct directory structure.

Solution: Verify your Django project structure and INSTALLED_APPS configuration:

# Check your project structure
myproject/
├── manage.py
├── myproject/
│   ├── __init__.py
│   ├── settings.py
│   └── urls.py
└── myapp/
    ├── __init__.py
    ├── models.py
    └── views.py

# In settings.py, ensure your app is registered
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'myapp',  # Your app must be listed here
]

Check that __init__.py files exist in all directories:

# Verify __init__.py files exist
find . -type d -name "myapp" -exec ls -la {}/.. \;

Q2: Flask blueprint import errors in modular applications #

Problem: ModuleNotFoundError when importing Flask blueprints or modules in structured Flask applications.

Solution: Ensure proper Flask application factory pattern and relative imports:

# app/__init__.py
from flask import Flask

def create_app():
    app = Flask(__name__)
    
    # Import blueprints after app creation to avoid circular imports
    from app.auth import auth_bp
    from app.main import main_bp
    
    app.register_blueprint(auth_bp)
    app.register_blueprint(main_bp)
    
    return app

# app/auth/routes.py
from flask import Blueprint
from app.models import User  # Correct relative import

auth_bp = Blueprint('auth', __name__)

Use absolute imports when running Flask with python -m:

# Run Flask module correctly
python -m flask run
# Instead of: python app.py

Q3: Django models import failing across apps #

Problem: Cannot import models from other Django apps, getting ModuleNotFoundError or ImportError.

Solution: Use proper Django model import patterns:

# Correct way to import models from other apps
from myapp.models import MyModel
from django.apps import apps

# Alternative using apps registry (recommended for complex cases)
MyModel = apps.get_model('myapp', 'MyModel')

# In models.py, use string references for foreign keys
class Order(models.Model):
    user = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    product = models.ForeignKey('shop.Product', on_delete=models.CASCADE)

Avoid circular imports in Django models:

# Instead of direct imports in models.py
from django.contrib.auth.models import User

# Use string reference
user = models.ForeignKey('auth.User', on_delete=models.CASCADE)

Q4: Flask extension import errors after installation #

Problem: Flask extensions installed via pip but import statements fail with ModuleNotFoundError.

Solution: Verify extension installation and import syntax:

# Check installed packages
import subprocess
import sys

result = subprocess.run([sys.executable, '-m', 'pip', 'list'], 
                       capture_output=True, text=True)
print(result.stdout)

# Common Flask extension import patterns
from flask_sqlalchemy import SQLAlchemy  # flask-sqlalchemy
from flask_migrate import Migrate        # flask-migrate
from flask_login import LoginManager     # flask-login
from flask_wtf import FlaskForm         # flask-wtf

# Initialize extensions correctly
app = Flask(__name__)
db = SQLAlchemy(app)
migrate = Migrate(app, db)

Q5: Django settings module not found in production #

Problem: ModuleNotFoundError: No module named 'myproject.settings' when deploying Django applications.

Solution: Configure Django settings module environment variable correctly:

# Set DJANGO_SETTINGS_MODULE environment variable
export DJANGO_SETTINGS_MODULE=myproject.settings

# For production with different settings
export DJANGO_SETTINGS_MODULE=myproject.settings.production

# In wsgi.py, ensure correct settings path
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')

Check your deployment configuration:

# wsgi.py or asgi.py
import os
import sys

# Add project directory to Python path
project_path = '/path/to/your/project'
if project_path not in sys.path:
    sys.path.append(project_path)

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')

Q6: Flask factory pattern circular import errors #

Problem: Circular import errors when using Flask application factory pattern with blueprints.

Solution: Structure imports to avoid circular dependencies:

# app/__init__.py - Correct factory pattern
from flask import Flask

def create_app(config_name='default'):
    app = Flask(__name__)
    
    # Import and register blueprints inside function
    from app.main import main_bp
    from app.auth import auth_bp
    
    app.register_blueprint(main_bp)
    app.register_blueprint(auth_bp, url_prefix='/auth')
    
    return app

# app/main/__init__.py
from flask import Blueprint

main_bp = Blueprint('main', __name__)

# Import routes at the end to avoid circular imports
from app.main import routes

# app/main/routes.py
from app.main import main_bp
from app.models import User  # Import models, not the app

Q7: Django command line import errors #

Problem: Custom Django management commands failing with import errors.

Solution: Structure Django commands properly:

# myapp/management/__init__.py (empty file required)

# myapp/management/commands/__init__.py (empty file required)

# myapp/management/commands/my_command.py
from django.core.management.base import BaseCommand
from myapp.models import MyModel  # Correct import path

class Command(BaseCommand):
    help = 'My custom command'
    
    def handle(self, *args, **options):
        # Command logic here
        pass

Run commands with proper module path:

# Correct way to run Django commands
python manage.py my_command

# Ensure DJANGO_SETTINGS_MODULE is set
export DJANGO_SETTINGS_MODULE=myproject.settings
python manage.py my_command

Quick Framework-Specific Troubleshooting #

Django Import Checklist #

Verify INSTALLED_APPS contains your apps

INSTALLED_APPS = ['myapp']

Check init.py files exist in all app directories

Use proper model import syntax

from myapp.models import MyModel

Set DJANGO_SETTINGS_MODULE correctly

Flask Import Checklist #

Use application factory pattern correctly

def create_app():
    app = Flask(__name__)
    from app.views import main_bp
    app.register_blueprint(main_bp)
    return app

Import blueprints inside factory function

Run Flask with module syntax

python -m flask run

Verify extension installation and import names

Most Python import module not found error solutions for Django and Flask involve proper project structure, correct import syntax, and avoiding circular dependencies. Follow these framework-specific patterns to resolve import issues effectively.