#coding:utf-8
from django.http import HttpResponse
def index(request):
return HttpResponse("index")
def detail(request,id):
return HttpResponse("detail %s" % id)
from django.contrib import admin
from django.conf.urls import include,url
urlpatterns = [
url(r'^', include('booktest.urls')),# 添加代码行
url(r'^admin/', admin.site.urls),
]
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index,name='index'),
url(r'^([0-9]+)/$', views.detail),
]
此时,在浏览器中输入对应url会显示相应界面
http://127.0.0.1:8000
http://127.0.0.1:8000/1/
'DIRS': [os.path.join(BASE_DIR, 'templates')],
{{输出值,可以是变量,也可以是对象.属性}}
{%执行代码段%}
首页
图书列表
{%for book in booklist%}
-
{{book.btitle}}
{%endfor%}
详细页
{{book.btitle}}
{%for hero in book.heroinfo_set.all%}
- {{hero.hname}}---{{hero.hcontent}}
{%endfor%}
from django.shortcuts import render
from models import BookInfo
def index(reqeust):
booklist = BookInfo.objects.all()
return render(reqeust, 'booktest/index.html', {'booklist': booklist})
def detail(reqeust, id):
book = BookInfo.objects.get(pk=id)
return render(reqeust, 'booktest/detail.html', {'book': book})
# 修改前代码
# 修改后代码
# 修改前代码
url(r'^', include('booktest.urls')),
# 修改后代码
url(r'^booktest/', include(('booktest.urls','booktest'),namespace="booktest")),
附一个学习过程中遇见的问题以及解决方法链接:
Question:
TypeError: context must be a dict rather than Context.
这是使用模板并返回HttpResponse时出的错误,在使用render函数后就可以解决,若仍要使用HttpResponse,可以参考Django 中遇到的问题(1)TypeError: context must be a dict rather than Context.进行修改。