Django项目部署到Heroku后出现ModuleNotFoundError: No module named 'my_app.urls'错误的解决咨询
Let's walk through the most common fixes for this issue, since your local setup works fine but Heroku is throwing this error:
1. Make sure your my_app directory is tracked by Git
Heroku only deploys files that are committed to your Git repository—it’s easy to accidentally forget to add new app directories.
- Run
git statusin your local project root. Look formy_app/in the "Untracked files" section. - If it’s missing, add and commit it:
git add my_app/ git commit -m "Add my_app directory and all its files" git push heroku main - Double-check that
my_app/urls.pyis included in the commit withgit show HEAD -- my_app/urls.py.
2. Verify your Python path on Heroku
Sometimes Heroku’s environment doesn’t include your project root in the Python path, which makes it unable to locate my_app.
- Add these temporary debug lines to your
settings.py:import os import sys print("BASE_DIR:", BASE_DIR) print("Python sys.path:", sys.path) - Deploy this change, then check your Heroku logs with:
heroku logs --tail - If
BASE_DIR(your project root) isn’t insys.path, add it manually insettings.py:if BASE_DIR not in sys.path: sys.path.append(BASE_DIR) - Remove the print statements once you confirm it works.
3. Clear Heroku's build cache
Old build caches can sometimes cause module resolution issues, even if your code is correct.
- Purge the cache and redeploy:
Replaceheroku repo:purge_cache -a your-app-name git push heroku mainyour-app-namewith the name of your Heroku app.
4. Fix ALLOWED_HOSTS for DEBUG=False issues
While this isn’t directly causing the ModuleNotFoundError, when DEBUG=False, Django requires properly configured ALLOWED_HOSTS to avoid 500 errors.
- Update your
settings.pyto include your Heroku app’s domain:ALLOWED_HOSTS = ['your-app-name.herokuapp.com', 'localhost', '127.0.0.1'] - For a flexible setup, use an environment variable:
Then set theimport os ALLOWED_HOSTS = os.environ.get("ALLOWED_HOSTS", "localhost,127.0.0.1").split(",")ALLOWED_HOSTSvariable in Heroku’s dashboard (Settings > Config Vars) to your app’s domain.
5. Double-check your INSTALLED_APPS configuration
While you’ve already added my_app to INSTALLED_APPS, try using the full config path just in case:
INSTALLED_APPS = [ # ... default apps 'my_app.apps.MyAppConfig', # Match the config class in my_app/apps.py ]
You can confirm the exact name in my_app/apps.py (the name attribute in the MyAppConfig class should be my_app).
After each step, deploy your changes and check if the error is resolved. Always use heroku logs --tail to get detailed server error messages—this will help you narrow down any remaining issues.
内容的提问来源于stack exchange,提问作者Abdulla Shafi

