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

Django报错ModuleNotFoundError: No module named 'myapp.urls'求助

解决ModuleNotFoundError: No module named 'myapp.urls'的步骤

1. 修复myapp/urls.py的语法错误

你的myapp/urls.py存在两处关键问题,这会直接导致模块加载失败:

  • 第二个path语句末尾缺少逗号,引发Python语法解析错误
  • 未导入当前app的views模块,无法识别views.index

修改后的代码:

from django.urls import path
from . import views  # 导入当前目录的views模块

urlpatterns = [
    path('', views.index ),
    path('create/', views.index),  # 补上缺失的逗号
    path('read/1/', views.index)
]

2. 修正views.py的代码错误

views.py存在两处逻辑/拼写错误,虽然不直接引发模块找不到问题,但会导致后续请求失败:

  • Httpresponse拼写错误,应为HttpResponse(大写R)
  • 函数未返回响应对象,仅创建了HttpResponse实例

修改后的代码:

from django.shortcuts import render, HttpResponse

def index(request):
    return HttpResponse('Welcome!')  # 加上return,修正拼写

3. 确认myapp的apps.py配置

检查myapp/apps.py,确保name字段严格为'myapp',配置如下:

from django.apps import AppConfig

class MyappConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'myapp'

4. 验证运行环境与命令

确保在项目根目录(包含manage.py的目录)下执行Django命令,示例:

python manage.py runserver

若使用IDE运行,检查运行配置的工作目录是否设置为项目根目录。

5. 清理缓存(可选)

若上述步骤无效,清理迁移缓存后重新初始化:

rm -rf myapp/migrations/__pycache__/
python manage.py makemigrations
python manage.py migrate

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 22:01:18