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