PyGuide

Learn Python with practical tutorials and code examples

Code Snippet Intermediate
• Updated Aug 5, 2025

Python Import Module Not Found Error Solutions Django Flask Code Examples

Ready-to-use Python code examples for fixing import module not found errors in Django and Flask. Practical snippets for common web framework import issues.

Python Import Module Not Found Error Solutions Django Flask Code Examples

When facing Python import module not found errors in Django and Flask applications, these ready-to-use code examples provide immediate solutions. Copy and adapt these snippets to resolve common web framework import issues.

Django Import Error Diagnostics #

Django Project Structure Validator #

🐍 Try it yourself

Output:
Click "Run Code" to see the output

Django INSTALLED_APPS Checker #

🐍 Try it yourself

Output:
Click "Run Code" to see the output

Flask Import Error Diagnostics #

Flask Application Structure Validator #

🐍 Try it yourself

Output:
Click "Run Code" to see the output

Flask Blueprint Import Resolver #

🐍 Try it yourself

Output:
Click "Run Code" to see the output

Django Import Fix Generators #

Django App Import Fixer #

#!/usr/bin/env python3
"""
Django app import error fixer
Automatically generates correct import statements for Django apps
"""

import os
import sys
from pathlib import Path

def generate_django_imports(app_name, target_models=None):
    """Generate correct Django import statements"""
    
    target_models = target_models or []
    
    print(f"=== Django Import Generator for '{app_name}' ===")
    
    # Basic app imports
    imports = {
        'models': f"from {app_name}.models import ",
        'views': f"from {app_name}.views import ",
        'forms': f"from {app_name}.forms import ",
        'urls': f"from {app_name} import urls as {app_name}_urls",
        'admin': f"from {app_name}.admin import ",
        'apps': f"from {app_name}.apps import {app_name.title()}Config"
    }
    
    # Generate model imports
    if target_models:
        model_imports = ", ".join(target_models)
        print(f"# Import specific models")
        print(f"from {app_name}.models import {model_imports}")
    else:
        print(f"# Import all models (not recommended for large apps)")
        print(f"from {app_name}.models import *")
    
    print(f"\n# Alternative model import using apps registry")
    print(f"from django.apps import apps")
    for model in target_models:
        print(f"{model} = apps.get_model('{app_name}', '{model}')")
    
    # Generate view imports
    print(f"\n# View imports")
    print(f"from {app_name}.views import MyView")
    print(f"from {app_name}.views import my_function_view")
    
    # Generate URL imports for main urls.py
    print(f"\n# URL configuration (in main urls.py)")
    print(f"from django.urls import path, include")
    print(f"")
    print(f"urlpatterns = [")
    print(f"    path('{app_name}/', include('{app_name}.urls')),")
    print(f"]")
    
    # Generate settings configuration
    print(f"\n# Settings.py configuration")
    print(f"INSTALLED_APPS = [")
    print(f"    'django.contrib.admin',")
    print(f"    'django.contrib.auth',")
    print(f"    'django.contrib.contenttypes',")
    print(f"    '{app_name}',  # Add your app here")
    print(f"]")

def create_django_app_structure(app_name):
    """Create proper Django app structure with __init__.py files"""
    
    app_path = Path(app_name)
    
    if app_path.exists():
        print(f"Directory '{app_name}' already exists")
        return False
    
    print(f"Creating Django app structure for '{app_name}'")
    
    # Create app directory
    app_path.mkdir()
    
    # Create essential files
    files_to_create = {
        '__init__.py': '',
        'admin.py': f'''from django.contrib import admin

# Register your models here.
''',
        'apps.py': f'''from django.apps import AppConfig


class {app_name.title()}Config(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = '{app_name}'
''',
        'models.py': f'''from django.db import models

# Create your models here.
''',
        'tests.py': f'''from django.test import TestCase

# Create your tests here.
''',
        'views.py': f'''from django.shortcuts import render

# Create your views here.
''',
        'urls.py': f'''from django.urls import path
from . import views

app_name = '{app_name}'
urlpatterns = [
    # Add your URL patterns here
]
'''
    }
    
    for filename, content in files_to_create.items():
        file_path = app_path / filename
        with open(file_path, 'w') as f:
            f.write(content)
        print(f"  ✓ Created {filename}")
    
    # Create migrations directory
    migrations_path = app_path / 'migrations'
    migrations_path.mkdir()
    
    with open(migrations_path / '__init__.py', 'w') as f:
        f.write('')
    
    print(f"  ✓ Created migrations/__init__.py")
    print(f"\nDjango app '{app_name}' structure created successfully!")
    
    return True

# Example usage
if __name__ == "__main__":
    app_name = "blog"
    models = ["Post", "Comment", "Tag"]
    
    generate_django_imports(app_name, models)
    print("\n" + "="*50)
    create_django_app_structure(app_name)

Flask Import Fix Generators #

Flask Application Factory Generator #

#!/usr/bin/env python3
"""
Flask application factory import error fixer
Generates proper Flask app structure with correct imports
"""

from pathlib import Path
import os

def create_flask_app_factory(app_name="myapp"):
    """Create Flask application factory structure"""
    
    app_path = Path(app_name)
    
    if app_path.exists():
        print(f"Directory '{app_name}' already exists")
        return False
    
    print(f"Creating Flask application factory for '{app_name}'")
    
    # Create app directory structure
    directories = [
        app_path,
        app_path / "app",
        app_path / "app" / "main", 
        app_path / "app" / "auth",
        app_path / "app" / "static",
        app_path / "app" / "templates"
    ]
    
    for directory in directories:
        directory.mkdir(parents=True, exist_ok=True)
        print(f"  ✓ Created directory: {directory}")
    
    # Create application factory files
    files_to_create = {
        # Main application factory
        "app/__init__.py": '''from flask import Flask

def create_app(config_name='default'):
    """Application factory pattern"""
    app = Flask(__name__)
    
    # Configure app
    app.config['SECRET_KEY'] = 'your-secret-key-here'
    
    # Import and register blueprints
    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
''',
        
        # Main blueprint
        "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 flask import render_template
from app.main import main_bp

@main_bp.route('/')
def index():
    return '<h1>Hello from Flask App Factory!</h1>'

@main_bp.route('/about')
def about():
    return '<h1>About Page</h1>'
''',
        
        # Auth blueprint
        "app/auth/__init__.py": '''from flask import Blueprint

auth_bp = Blueprint('auth', __name__)

# Import routes at the end to avoid circular imports
from app.auth import routes
''',
        
        "app/auth/routes.py": '''from flask import render_template, request, redirect, url_for
from app.auth import auth_bp

@auth_bp.route('/login')
def login():
    return '<h1>Login Page</h1>'

@auth_bp.route('/register')
def register():
    return '<h1>Register Page</h1>'
''',
        
        # Main application entry point
        f"{app_name}.py": '''#!/usr/bin/env python3
import os
from app import create_app

app = create_app(os.getenv('FLASK_CONFIG', 'default'))

if __name__ == '__main__':
    app.run(debug=True)
''',
        
        # Requirements file
        "requirements.txt": '''Flask>=2.0.0
python-dotenv>=0.19.0
''',
        
        # Environment configuration
        ".env": '''FLASK_APP=myapp.py
FLASK_ENV=development
SECRET_KEY=your-secret-key-here
''',
        
        # Configuration file
        "config.py": '''import os

class Config:
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard-to-guess-string'

class DevelopmentConfig(Config):
    DEBUG = True

class ProductionConfig(Config):
    DEBUG = False

config = {
    'development': DevelopmentConfig,
    'production': ProductionConfig,
    'default': DevelopmentConfig
}
'''
    }
    
    for file_path, content in files_to_create.items():
        full_path = app_path / file_path
        full_path.parent.mkdir(parents=True, exist_ok=True)
        
        with open(full_path, 'w') as f:
            f.write(content)
        print(f"  ✓ Created {file_path}")
    
    print(f"\nFlask application factory '{app_name}' created successfully!")
    
    # Generate usage instructions
    print(f"\n=== Usage Instructions ===")
    print(f"1. cd {app_name}")
    print(f"2. python -m venv venv")
    print(f"3. source venv/bin/activate  # On Windows: venv\\Scripts\\activate")
    print(f"4. pip install -r requirements.txt")
    print(f"5. python {app_name}.py")
    
    return True

def generate_flask_blueprint_template(blueprint_name):
    """Generate Flask blueprint template with correct imports"""
    
    print(f"=== Flask Blueprint Template: {blueprint_name} ===")
    
    # Blueprint __init__.py
    init_template = f'''from flask import Blueprint

{blueprint_name}_bp = Blueprint('{blueprint_name}', __name__)

# Import routes at the end to avoid circular imports
from app.{blueprint_name} import routes
'''
    
    # Blueprint routes.py
    routes_template = f'''from flask import render_template, request, jsonify
from app.{blueprint_name} import {blueprint_name}_bp

@{blueprint_name}_bp.route('/')
def index():
    return f'<h1>{blueprint_name.title()} Blueprint Index</h1>'

@{blueprint_name}_bp.route('/api/data')
def api_data():
    return jsonify({{'message': 'Data from {blueprint_name} blueprint'}})
'''
    
    # Registration in main app
    registration_template = f'''# Add to app/__init__.py create_app() function:

from app.{blueprint_name} import {blueprint_name}_bp
app.register_blueprint({blueprint_name}_bp, url_prefix='/{blueprint_name}')
'''
    
    print("=== Blueprint __init__.py ===")
    print(init_template)
    
    print("\n=== Blueprint routes.py ===")
    print(routes_template)
    
    print("\n=== Registration in main app ===")
    print(registration_template)

# Example usage
if __name__ == "__main__":
    # Create Flask app with factory pattern
    create_flask_app_factory("myflaskapp")
    
    print("\n" + "="*50)
    
    # Generate blueprint template
    generate_flask_blueprint_template("api")

Web Framework Import Error Resolver #

Universal Web Framework Import Fixer #

🐍 Try it yourself

Output:
Click "Run Code" to see the output

Summary #

These Python import module not found error solutions for Django and Flask provide comprehensive code examples for diagnosing and fixing common web framework import issues. Use the diagnostic scripts to identify problems, the structure validators to ensure proper project organization, and the generators to create correct import patterns.

Copy and customize these snippets to resolve import errors in your Django and Flask applications efficiently.

Related Snippets

Snippet Beginner

Python Dictionary Iteration Examples: Ready-to-Use Code

Ready-to-use Python code examples for iterating over dictionaries including keys, values, items, and advanced iteration patterns.

#python #dictionary #iteration +2
View Code
Data Structures
Snippet Intermediate

Python Error Frame Inspection Code Examples

Ready-to-use Python code snippets for inspecting error frames, analyzing stack traces, and debugging frame-related issues effectively.

#python #error #frame +2
View Code
Syntax
Snippet Intermediate

Python Error Handling Code Snippets: Try-Except Examples

Ready-to-use Python error handling code snippets. Copy-paste examples for common error handling patterns and exception management.

#python #error #exception +2
View Code
Syntax
Snippet Intermediate

Python What Error to Raise: Code Examples and Patterns

Practical code snippets showing what error to raise in Python. Copy-paste examples for ValueError, TypeError, AttributeError, and custom exceptions.

#python #exceptions #raise +2
View Code
Syntax