你是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
我的文件夹看起来像这样
有人可以帮我解决这个问题。
答案 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'),