Python Django NameError:未定义名称“视图”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24650261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:56:59  来源:igfitidea点击:

Django NameError: name 'views' is not defined

pythondjango

提问by user3181236

I am working through this tutorialon rapid site development with Django.

我正在学习有关快速网站开发的本教程Django.

I have followed it exactly (as far as I can see), but get the following error when I try to view the index page:

我完全遵循了它(就我所见),但是当我尝试查看索引页面时出现以下错误:

NameError at /name 'views' is not defined
Exception location: \tuts\urls.py in <module>, line 12

Here's urls.py:

这是urls.py

from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',

    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', views.index, name='index'),
)

Here's views.py:

这是views.py

from django.shortcuts import render

# Create your views here.
def index(request):
    items = Item.objects.order_by("-publish_date")
    now = datetime.datetime.now()
    return render(request,'portfolio/index.html', {"items": items, "year": now.year})

And here's models.py:

这是models.py

from django.db import models

# Create your models here.
class Item(models.Model):
    publish_date = models.DateField(max_length=200)
    name = models.CharField(max_length=200)
    detail = models.CharField(max_length=1000)
    url = models.URLField()
    thumbnail = models.CharField(max_length=200)

I also have a basic index.htmltemplate in place. From looking around I think I need to import my view somewhere.

我也有一个基本的index.html模板。从环顾四周,我想我需要在某处导入我的视图。

But I'm completely new to Django so I have no clue. Any ideas?

但我对 Django 完全陌生,所以我不知道。有任何想法吗?

回答by Rohan

The error line is

错误行是

    url(r'^$', views.index, name='index'),
    #----------^

Here viewsis not defined, hence the error. You need to import it from your app.

这里views没有定义,因此出现错误。您需要从您的应用程序中导入它。

in urls.py add line

在 urls.py 添加行

from <your_app> import views
# replace <your_app> with your application name.

回答by Chirag Kanzariya

from .views import index
  • here we have to import views model classes on urls model so above sentence import your view model class on urls model.
  • 在这里,我们必须在 urls 模型上导入视图模型类,因此上面的句子在 urls 模型上导入您的视图模型类。

add this code in urls.py

在 urls.py 中添加此代码