PyCharm搭建Django——(三)视图&模版
一、视图
- 在django中,视图对WEB请求进行回应
- 视图接收reqeust对象作为第一个参数,包含了请求的信息
- 视图就是一个Python函数,被定义在views.py中
#coding:utf-8
from django.http import HttpResponse
def index(request):
return HttpResponse("index")
def detail(request,id):
return HttpResponse("detail %s" % id)
- 定义完成视图后,需要配置urlconf,否则无法处理请求
二、URLconf
- 在Django中,定义URLconf包括正则表达式、视图两部分
- Django使用正则表达式匹配请求的URL,一旦匹配成功,则调用应用的视图
- 注意:只匹配路径部分,即除去域名、参数后的字符串
- 在DjangoProject/urls.py插入booktest,使主urlconf连接到booktest.urls模块
from django.contrib import admin
from django.conf.urls import include,url
urlpatterns = [
url(r'^', include('booktest.urls')),# 添加代码行
url(r'^admin/', admin.site.urls),
]
- 在booktest中的urls.py中添加urlconf
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/
三、模板
- 模板是html页面,可以根据视图中传递的数据填充值
- 创建模板的目录如下图:
- 修改settings.py文件,设置TEMPLATES的DIRS值
'DIRS': [os.path.join(BASE_DIR, 'templates')],
- 在模板中访问视图传递的数据
{{输出值,可以是变量,也可以是对象.属性}}
{%执行代码段%}
定义模板
- index.html模板
<!DOCTYPE html>
<html>
<head>
<title>首页</title>
</head>
<body>
<h1>图书列表</h1>
<ul>
{%for book in booklist%}
<li>
<a href="{{book.id}}">
{{book.btitle}}
</a>
</li>
{%endfor%}
</ul>
</body>
</html>
- detail.html模板
<!DOCTYPE html>
<html>
<head>
<title>详细页</title>
</head>
<body>
<h1>{{book.btitle}}</h1>
<ul>
{%for hero in book.heroinfo_set.all%}
<li>{{hero.hname}}---{{hero.hcontent}}</li>
{%endfor%}
</ul>
</body>
</html>
使用模板
- 编辑views.py文件,在方法中调用模板。Django提供了函数Render()简化视图调用模板、构造上下文
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})
去除模版硬编码
- 在index.html模板中,超链接是硬编码的
# 修改前代码
<a href="{{book.id}}">
# 修改后代码
<a href="{%url 'booktest:detail' book.id%}">
- 同时需修改DjangoProject/urls.py中的url代码
# 修改前代码
url(r'^', include('booktest.urls')),
# 修改后代码
url(r'^booktest/', include(('booktest.urls','booktest'),namespace="booktest")),
- 最后可以在浏览器中测试效果了
http://127.0.0.1:8000/booktest/
点击对应书名可以跳转到Hero的详细页面
http://127.0.0.1:8000/booktest/book/1/
最后
附一个学习过程中遇见的问题以及解决方法链接:
Question:
TypeError: context must be a dict rather than Context.
这是使用模板并返回HttpResponse时出的错误,在使用render函数后就可以解决,若仍要使用HttpResponse,可以参考Django 中遇到的问题(1)TypeError: context must be a dict rather than Context.进行修改。