例外价值:名称'时事通讯'没有定义 - python

时间:2015-06-21 06:18:37

标签: python django

你是python和Django的新手。

我刚刚创建了一个名为newsletter

的新应用

视图

from django.shortcuts import render

# Create your views here.

def home(request):
    return render(request, "home.html", {})

Urls.py文件

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [


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

当我尝试在浏览器中访问它时,http://127.0.0.1:8000/newsletter我收到错误。

NameError at /newsletter
name 'newsletter' is not defined
Request Method: GET
Request URL:    http://127.0.0.1:8000/newsletter
Django Version: 1.8.2
Exception Type: NameError
Exception Value:    
name 'newsletter' is not defined
Exception Location: /home/baman/Desktop/trydjango18/src/trydjango18/urls.py in <module>, line 23
Python Executable:  /home/baman/Desktop/trydjango18/bin/python
Python Version: 2.7.6
Python Path:    
['/home/baman/Desktop/trydjango18/src',
 '/home/baman/Desktop/trydjango18/lib/python2.7',
 '/home/baman/Desktop/trydjango18/lib/python2.7/plat-x86_64-linux-gnu',
 '/home/baman/Desktop/trydjango18/lib/python2.7/lib-tk',
 '/home/baman/Desktop/trydjango18/lib/python2.7/lib-old',
 '/home/baman/Desktop/trydjango18/lib/python2.7/lib-dynload',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-x86_64-linux-gnu',
 '/usr/lib/python2.7/lib-tk',
 '/home/baman/Desktop/trydjango18/local/lib/python2.7/site-packages',
 '/home/baman/Desktop/trydjango18/lib/python2.7/site-packages']
Server time:    Sun, 21 Jun 2015 06:10:08 +0000

我的文件夹看起来像这样

enter image description here

有人可以帮我解决这个问题。

1 个答案:

答案 0 :(得分:2)

您必须将newsletter申请添加到INSTALLED_APPS

中的settings.py部分

示例

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'newsletter',
)

这让Django项目知道有一个名为newsletter

的应用程序

现在您需要将newsletter导入urls.py作为

from django.conf.urls import include, url
from django.contrib import admin

#newly added
import newsletter

urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', newsletter.views.home, name='home'),
]

注意建议您为应用程序添加新的urls.py,然后将该文件包含在主文件中。

那是

项目url.py必须看起来像

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', include('newsletter.urls') ), #Changed here
    ]

可以在应用程序内部编写url映射,newsletters url映射文件,url.py

# Newly added file in the newsletter directory
from django.conf.urls import patterns, url
from newsletter import views

urlpatterns = patterns('',
        url(r'^$', views.home, name='home'),