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

Django中使用path('challenges/',include(challenges.urls))报NameError求助

问题描述

注释代码时:

urlpatterns = [
   path('admin/', admin.site.urls),
   #path('challenges/',include(challenges.urls))
]

程序运行正常,但使用以下代码时:

urlpatterns = [
   path('admin/', admin.site.urls),
   path('challenges/',include(challenges.urls))
]

出现报错:NameError: name 'challenges' is not defined

请问为何使用该代码时会出现此错误?


问题解答

这个错误的核心原因是:你代码里用到的challenges名称没有被Python识别——当前urls.py文件中没有导入challenges模块。

当你注释掉那行代码时,Python不会执行它,自然不会检查challenges是否存在;但取消注释后,Python执行include(challenges.urls)时,找不到名为challenges的模块,就会抛出NameError。

解决方法有两种:

  1. 直接导入模块
    在当前urls.py文件顶部添加导入语句:
# 方式一:直接导入challenges模块
import challenges
# 方式二:仅导入urls并别名(更清晰)
from challenges import urls as challenges_urls
# 对应path写法:path('challenges/', include(challenges_urls))
  1. 使用字符串形式传入include(Django推荐写法)
    不需要导入模块,直接用字符串指定app的urls路径:
path('challenges/', include('challenges.urls'))

这种写法更灵活,也能直接规避这类导入报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 23:22:33