You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

运行Django服务器时出现404错误:index.html未找到,如何解决?

Fixing the "index.html could not be found" 404 Error in Django

Hey there, let's sort out that 404 error you're hitting when accessing http://127.0.0.1:8000/. The error points to Django's staticfiles module failing to locate your index.html, so this is almost always a file placement or configuration issue. Here's how to troubleshoot it:

1. Verify your index.html location

First, double-check where you've placed index.html. Django looks for static files in specific directories:

  • If you're using an app-specific static folder, it should live at your_app/static/index.html
  • If you're using a project-wide static folder, it should be at your_project/static/index.html

Make sure the file isn't nested in extra subfolders unless you've configured paths to account for that.

2. Check your static file settings in settings.py

Open your project's settings.py and confirm these key configurations:

  • Ensure DEBUG = True (static file auto-serving only works in debug mode for development)
  • Confirm django.contrib.staticfiles is listed in INSTALLED_APPS
  • If you're using a project-wide static folder, add it to STATICFILES_DIRS like this:
    STATICFILES_DIRS = [
        BASE_DIR / "static",
    ]
    
    (Where BASE_DIR is the auto-generated root path of your project)
  • STATIC_URL should be set to /static/ (the default) unless you've intentionally changed it—if you did, make sure your file paths align with this value.

3. Confirm your URL routing is set up correctly

Since the error is triggered by django.contrib.staticfiles.views.serve, you need a route that maps the root URL (/) to your index.html. Add this to your project's urls.py:

from django.contrib.staticfiles.views import serve
from django.urls import path

urlpatterns = [
    # Your other app routes go here...
    path('', serve, {'path': 'index.html'}),
]

4. Quick checks for edge cases

  • File name sensitivity: On Linux/macOS, filenames are case-sensitive—make sure it's exactly index.html (not Index.html or INDEX.HTML)
  • File permissions: Ensure your server has read access to the index.html file
  • Clear static file cache: If you've made changes recently, restart your Django dev server to clear any cached paths. You can also run python manage.py collectstatic (though this is mainly for production, it can help resolve path mismatches in development too).

Once you've gone through these steps, restart your dev server and try accessing the root URL again—this should resolve the 404.

内容的提问来源于stack exchange,提问作者uitwaa

火山引擎 最新活动