在Heroku部署Django应用时出现ModuleNotFoundError错误求助
Hey there, let's get this Django deployment issue sorted out—this is a super common hiccup when pushing apps to Heroku, so we'll have it fixed in no time.
1. Ensure you have a requirements.txt file
Heroku relies on this file to install all the dependencies your app needs, and right now it doesn't know it needs Django. Here's how to set it up:
- Activate your local virtual environment (if you're using one—you should be for Django projects!)
- Run this command in your project root folder:
pip freeze > requirements.txt
This exports all your locally installed packages into the file. Double-check that django==[your-exact-version] (like django==3.2.19) is listed—if it's missing, add it manually.
2. Swap runserver for a production-ready server
The python manage.py runserver command is only for local development. Heroku recommends using Gunicorn as your WSGI server:
- Install Gunicorn locally first:
pip install gunicorn - Update your
requirements.txtagain withpip freeze > requirements.txtto include Gunicorn - Create a file named
Procfile(no file extension) in your project root, and add this line:
Replaceweb: gunicorn your_project_name.wsgi --log-file -your_project_namewith the name of the folder that holds yourwsgi.pyandsettings.pyfiles.
3. Push the updates to Heroku
Run these Git commands to send your new configuration to Heroku:
git add requirements.txt Procfile git commit -m "Add dependencies and production server config for Heroku" git push heroku master
Quick troubleshooting if it still fails
- Did you forget to activate your virtual environment before running
pip freeze? If you used global packages, yourrequirements.txtmight not have the right versions. - Make sure you're pushing the correct Git branch—if you're working on a branch other than
master, usegit push heroku your-branch-name:master.
Your original error log for reference:
2018-05-03T14:35:40.682441+00:00 heroku[web.1]: Starting process with command `python manage.py runserver` 2018-05-03T14:35:41.960741+00:00 app[web.1]: Traceback (most recent call last): 2018-05-03T14:35:41.960765+00:00 app[web.1]: File "manage.py", line 8, in <module> 2018-05-03T14:35:41.960858+00:00 app[web.1]: from django.core.management import execute_from_command_line 2018-05-03T14:35:41.960872+00:00 app[web.1]: ModuleNotFoundError: No module named 'django'
内容的提问来源于stack exchange,提问作者Dimmy Magalhães

