Django应用嵌套至apps文件夹后导入失败的技术求助
apps Folder Hey there! It sounds like you’ve got your Django project’s apps nicely organized into an apps folder, set up the path in settings.py, and adjusted the name in each app’s apps.py—and the project runs fine, but you’re hitting snags when running unit tests individually. That’s a super common gotcha with nested Django apps, so let’s break down how to fix it:
Why This Happens
When you run tests for a single app (like python manage.py test myappname), Django relies on the app’s full canonical name (set in apps.py as apps.myappname) to locate its test modules. Even though you’ve added apps to sys.path and used the short name in INSTALLED_APPS, the test runner needs the full name to map things correctly behind the scenes.
Solutions to Try
1. Run Tests with the Full App Name
Instead of using the short name from INSTALLED_APPS, use the full name you set in apps.py:
python manage.py test apps.myappname
This tells Django exactly where to look for the app’s tests, and should resolve most "app not found" or import errors right away.
2. Clean Up Import Paths in Test Files
If you’re using absolute imports like from myappname.models import MyModel in your tests, switch to either:
- Relative imports (the Django-recommended approach):
from .models import MyModel - Full canonical imports:
from apps.myappname.models import MyModel
Relative imports are cleaner here, as they don’t depend on the project’s path setup.
3. Don’t Run Test Files Directly (Use manage.py test)
If you’re trying to run a single test file with something like python apps/myappname/tests.py, Django won’t load its full configuration automatically. Always use the manage.py test command—either for the whole app, a specific test file, or even a single test case:
# Run all tests for the app python manage.py test apps.myappname # Run a specific test file python manage.py test apps.myappname.tests.test_models # Run a single test case python manage.py test apps.myappname.tests.test_models.MyModelTestCase
If you absolutely need to run a test file directly (not recommended), add this configuration boilerplate at the top of the test file:
import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'your_project_name.settings') django.setup() # Rest of your test code
4. Double-Check App Config Consistency
It’s easy to miss one app when updating apps.py—quickly verify that every app in apps/ has:
name = 'apps.myappname'in itsapps.py- The short name
myappnamelisted inINSTALLED_APPS
A mismatch here can cause silent failures in tests even if the main project runs fine.
内容的提问来源于stack exchange,提问作者David Dahan

