Django+React部署至Heroku遇TemplateDoesNotExist(index.html)错误求助
Hey there, let's work through this TemplateDoesNotExist issue together! I've run into similar headaches deploying Django + React apps to Heroku, so here are the key fixes to check step by step:
1. Fix the Syntax Error in urls.py
First off, I noticed a small but critical typo in your urls.py code:
# Your current code (missing closing parenthesis) re_path(r'^.*', TemplateView.as_view(template_name='index.html'), # Corrected version re_path(r'^.*$', TemplateView.as_view(template_name='index.html'))
The missing ) at the end could cause unexpected routing issues on Heroku (even if it worked locally due to Django's lenient parsing in debug mode). Using r'^.*$' also ensures we match every possible path explicitly.
2. Verify Heroku is Building Your React App Correctly
Your postinstall script looks right, but Heroku might not be running it if the Node.js buildpack isn't set up properly. Here's how to fix that:
- Add the Node.js buildpack first (so npm dependencies install and build run before Python):
heroku buildpacks:add heroku/nodejs --index 1 heroku buildpacks:add heroku/python --index 2 - Check your Heroku logs to confirm the build step runs:
Look for lines likeheroku logs --tailRunning npm run buildorSuccessfully built React app—if you don't see these, the build isn't happening, so thebuildfolder won't exist on Heroku.
3. Make Sure Your Template Path is Reliable
Using os.path.join can sometimes cause cross-platform path issues. Switch to pathlib (available in Python 3.4+) for more consistent path handling in settings.py:
# Replace os import with pathlib from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent # Update TEMPLATES DIRS TEMPLATES = [ { # ... other settings 'DIRS': [BASE_DIR / 'build'], # ... }, ]
This ensures Django always looks for index.html in the correct build directory, regardless of the environment.
4. Confirm the build Folder Exists on Heroku
Sometimes the build script fails silently. Jump into a Heroku dyno to check:
heroku run bash
Once inside, run ls build—you should see index.html and a static folder. If the build folder is missing, double-check your package.json scripts (ensure build points to react-scripts build or your correct build command) and that Node.js dependencies are installing without errors.
5. Tweak Production Settings for Safety
While not directly causing the template error, it's good practice to update these for production:
- Set
DEBUG = Falseinsettings.py(keep it True only for local dev) - Restrict
ALLOWED_HOSTSto your actual domain:ALLOWED_HOSTS = ['temp-app-test.herokuapp.com']
Final Troubleshooting Step
If none of the above works, re-deploy after clearing Heroku's build cache:
heroku plugins:install heroku-builds heroku builds:cache:purge git commit --allow-empty -m "Purge cache" git push heroku main
That should cover most cases! Let me know if you hit any snags along the way.
内容的提问来源于stack exchange,提问作者zxcv

