You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django项目配置报错求助:按教程修改urls后出现异常

Fixing Your Django URL Configuration Issues

Hey there, let's break down what's causing the errors in your Django project and get it back on track!

The Key Problems in Your Modified urls.py (note: you named it fistsite.py but this is likely your project root urls.py)

  • Incorrect URL path formatting: Django's path() does not expect paths to start with a leading slash. Your lines like path('/polls', views.polls, name='polls') will fail to match requests because of that leading /.
  • Missing/conflicting view functions: You imported from . import views, but it's clear you haven't defined index, polls, or admin view functions in your root views.py (if you even have one!). On top of that, naming a view admin directly conflicts with Django's built-in admin module, which will cause even more issues.
  • Broken route splitting: You removed the include('polls.urls') line, which was correctly delegating Polls app routes to the app's own urls.py file. This is Django's recommended way to organize routes, and removing it breaks access to your Polls app entirely.

The Corrected Root urls.py

If your goal is to add a homepage (at the root / path) while keeping the Admin and Polls functionality working, use this configuration:

from django.contrib import admin
from django.urls import path, include
# Import your homepage view (adjust the import path if your view is in the Polls app)
from . import views

urlpatterns = [
    path('', views.index, name='index'),  # Root path for your homepage
    path('admin/', admin.site.urls),  # Keep Django's built-in Admin route
    path('polls/', include('polls.urls')),  # Keep Polls app route delegation
]

Additional Steps to Fix the Views

Make sure you have a views.py file in your project root (or adjust the import if your view is in the Polls app) with the index function defined:

from django.http import HttpResponse

def index(request):
    return HttpResponse("Welcome to the homepage!")

Quick Best Practices Reminders

  • Never name your own views/functions admin—it clashes with Django's core admin system.
  • Use include() to delegate routes to app-specific urls.py files, this keeps your project organized as it grows.
  • Always omit leading slashes in path() definitions; Django handles the root slash for you.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:54:21