python - 名称错误 : name 'index' is not defined

标签 python django

我已经开始了我的第一个 django 项目,但在向我的 urlpatters 添加 View 时遇到了问题。

project/first_app/views.py

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def index(request):
    return HttpResponse('test')

project/project/urls.py

from django.contrib import admin
from django.urls import path
from first_app import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name=index),
]

这在我的服务器终端中抛出以下错误

  File "/xxx/xxx/xxx/xxx/xxx/project/project/urls.py", line 22, in <module>
path('first_app', views.index, name=index),
NameError: name 'index' is not defined

我已经尝试了很多次路径:path('first_app'),但似乎无法让它工作。

最佳答案

这与您调用哪个网址无关。你的代码中的某个地方有 --Index-- 没有正确定义,这显然是一个没有定义的 python 变量。将 --index-- 作为字符串来命名路径中的参数,如下所示。

更改您的网址来源:

path('', views.index, name=index),

致:

 path('', views.index, name='index'),

了解更多信息: 请参阅此示例 django path

关于python - 名称错误 : name 'index' is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55432325/

相关文章:

python - Django 迁移和可解构字符串

django - 使用枚举作为选项获取选项显示值

python - 如何解决错误 : Failed building wheel for h5py

python - 在 Django 中进行迁移时出现 TransactionManagementError “Transaction managed block ended with pending COMMIT/ROLLBACK"

python - 关闭 Dask LocalCluster 的 "right"方法是什么?

python - 使用 python 2.7 中的请求模块验证是否发生了登录

Python/Keras/Theano - 值错误 : Dimension mismatch; shapes are (98, 10), (98, 1)

django - PyCharm3,如何摆脱 "cannot resolve directory"消息?

python - mypy 在导入子模块 : Module has no attribute 时出错

django - 如何在表单字段上设置 tabindex?