我是Django(1.11)和Python(2.7)的新手。我正在尝试创建一个博客。我在将URL映射到视图时遇到问题。
我的myblog\posts\views.py
:
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def post_home(request):
return HttpResponse("<h1>Hello</h1")
我的myblog\myblog\urls.py
:
from django.conf.urls import url
from django.contrib import admin
from posts import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^posts/$', posts_view.post_home),
]
我的myblog\myblog\settings.py
:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'posts',
]
TypeERROR:对于include(),视图必须是可调用的或列表/元组
任何帮助将不胜感激!
答案 0 :(得分:1)
您发布的代码中存在一些问题:
from posts import views
urlpatterns = [
url(r'^posts/$', posts_view.post_home),
# ^^^^^^^^^^
# what does this variable refer to ?
]
您使用语句posts.views
导入了模块(也称为python文件)from posts import views
,因此您必须以这种方式引用post_home
函数:
urlpatterns = [
# [...]
url(r'^posts/$', views.post_home),
]
那应该可以解决您的问题
注意:有很多方法可以引用您的视图函数:
示例1
import posts.views
urlpatterns = [
# [...]
url(r'^posts/$', posts.views.post_home),
]
示例2
from posts.views import post_home
urlpatterns = [
# [...]
url(r'^posts/$', post_home),
]
答案 1 :(得分:0)
将导入更改为:
from posts.views import post_home
和您的网址:
url(r'^posts/$', post_home),