NameError name 'Views' is not defined

折月煮酒 提交于 2019-12-11 13:38:23

问题


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)),
]  

After running the server there is an error "NameError: name 'views' is not defined"

Any help ??


回答1:


You aren't importing your own views.

Try adding this to your urls.py:

from . import views

Or if you are importing them from a specific app, try replacing . with the app name




回答2:


First thing I notice is the import *, realize that this will/can cause confusion for other Developers reading your scripts. Python has a methodology that insists that explicit is better than implicit. Which in this senario means you should be explicit about what you are importing.

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)),
]  

Here instead of importing everything from collection I'm importing just your views and assigning them to a variable. Then using that variable in the URL definitions.




回答3:


Be sure to import your views by specifying its location and the methods inside the view to be imported on your urls.py.

from . collection import *

(line above means from current location find collection.py and import everything on it)

Happy coding!



来源:https://stackoverflow.com/questions/38404491/nameerror-name-views-is-not-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!