嗨,我是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


我的文件夹看起来像这样



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

最佳答案

您必须将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
    ]


网址映射可以写在应用程序newsletters网址映射文件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'),

关于python - 异常值:名称“newsletter”未定义-python,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30961837/

10-12 18:27