【问题标题】:NameError name 'Views' is not definedNameError 名称“视图”未定义
【发布时间】:2016-11-19 03:48:32
【问题描述】:
from django.conf.urls import url, patterns, include
from django.contrib import admin
from django.views.generic import TemplateView
from collection import *


#from collection.views import index,thing_detail,edit_thing

urlpatterns = [ 
        url(r'^$', views.index, name='home'),
        url(r'^about/$',TemplateView.as_view(template_name='about.html'),name='about'),
        url(r'^contact/$',TemplateView.as_view(template_name='contact.html'),name='contact'),
        url(r'^things/(?P<slug>[-\w]+)/$', 'views.thing_detail' ,name='thing_detail'),
        url(r'^things/(?P<slug>[-\w]+)/edit/$', 'views.edit_thing',name='edit_thing'), 
        url(r'^admin/', include(admin.site.urls)),
]  

运行服务器后出现错误“NameError: name 'views' is not defined”

有什么帮助吗??

【问题讨论】:

  • 您没有导入自己的视图
  • 如果collection 是您的app 名称,我建议将from collection import * 更改为from collection import views,具体view 是什么
  • 首先明确导入您的视图。还要避免在 url ('views.edit_thing') 中使用字符串,因为它会引发弃用警告并且也不是一个好习惯。最后使用可调用视图本身edit_thing 而不是views.edit_thing

标签: django python-2.7 django-views


【解决方案1】:

您没有导入自己的视图。

尝试将此添加到您的urls.py

from . import views

或者,如果您是从特定应用导入它们,请尝试将 . 替换为应用名称

【讨论】:

  • 这可能会解决问题,但相对导入不是一个好主意。 stackoverflow.com/questions/4209641/…
  • URL 在 Django 中是如何工作的,我觉得相对导入不会让任何人感到困惑
  • Python 2.1.2务实胜于教条
【解决方案2】:

我注意到的第一件事是import *,意识到这将/可能导致其他开发人员阅读您的脚本时感到困惑。 Python 有一个methodology,它坚持explicit is better than implicit。在这种情况下,这意味着您应该明确说明要导入的内容。

from django.conf.urls import url, patterns, include
from django.contrib import admin
from django.views.generic import TemplateView
from collection import views as collection_views

urlpatterns = [ 
        # Function Based Views
        url(r'^$', collection_views.index, name='home'),
        url(r'^things/(?P<slug>[-\w]+)/$', collection_views.thing_detail ,name='thing_detail'),
        url(r'^things/(?P<slug>[-\w]+)/edit/$', collection_views.edit_thing,name='edit_thing'), 
        # Class Based Views            
        url(r'^about/$',TemplateView.as_view(template_name='about.html'),name='about'),
        url(r'^contact/$',TemplateView.as_view(template_name='contact.html'),name='contact'),
        # Admin
        url(r'^admin/', include(admin.site.urls)),
]  

这里不是从集合中导入所有内容,而是只导入您的视图并将它们分配给一个变量。然后在 URL 定义中使用该变量。

【讨论】:

    【解决方案3】:

    请务必通过以下方式导入您的视图 在 urls.py 中指定要导入的视图中的位置和方法。

    from . collection import *
    

    (上面的行表示从当前位置找到collection.py并导入上面的所有内容)

    编码愉快!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-27
      • 1970-01-01
      • 2018-01-24
      • 1970-01-01
      • 2012-01-18
      • 1970-01-01
      • 2021-04-15
      相关资源
      最近更新 更多