Django开发报错:包含的URLconf无匹配模式,求排查方案
Django URLconf无匹配模式错误排查与解决
错误信息
The included URLconf '<module 'myapp.urls' from 'C:\Users\Hp\Desktop\Python\Django Projects\myproject\myapp\urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import.
相关代码文件
myapp/urls.py
from django.urls import path from . import views urlpatterns=[ path('', views.index, name='index') ]
myapp/views.py
from django.shortcuts import render from django import HttpResponse # Create your views here. def index(request): return HttpResponse('<h1>Hey, Welcome</h1>')
项目根目录/urls.py
"""myproject URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')), ]
错误原因与解决步骤
1. 修复views.py的导入错误
views.py中HttpResponse的导入路径错误,正确路径是django.http而非django。这个错误会导致views模块加载失败,使得myapp.urls中的views.index无法被识别,最终Django判定urlpatterns无有效模式。
修改后代码:
from django.shortcuts import render from django.http import HttpResponse # 修正导入路径 def index(request): return HttpResponse('<h1>Hey, Welcome</h1>')
2. 验证应用注册状态
确保myapp已添加到项目根目录settings.py的INSTALLED_APPS列表中:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', # 确认该行存在 ]
3. 排查循环导入(可选)
若上述步骤无效,检查是否存在循环导入:
- 确认
myapp.urls未导入根目录urls模块 - 确认
views.py未导入任何间接引用urls模块的代码
4. 清理缓存并重启服务
删除项目中所有__pycache__文件夹,然后重启Django开发服务器,避免旧缓存干扰代码执行。
内容的提问来源于stack exchange,提问作者Shreyansh Sharma
相关产品推荐
相关产品推荐

