Django 视图和模板1.4
生活随笔
收集整理的這篇文章主要介紹了
Django 视图和模板1.4
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
視圖
- 在django中,視圖對WEB請求進行回應
- 視圖接收reqeust對象作為第一個參數,包含了請求的信息
- 視圖就是一個Python函數,被定義在views.py中
#coding:utf-8
from django.http import HttpResponsedef index(request):return HttpResponse("index")
def detail(request,id):return HttpResponse("detail %s" % id)
- 定義完成視圖后,需要配置urlconf,否則無法處理請求
URLconf
- 在Django中,定義URLconf包括正則表達式、視圖兩部分
- Django使用正則表達式匹配請求的URL,一旦匹配成功,則調用應用的視圖
- 注意:只匹配路徑部分,即除去域名、參數后的字符串
- 在test1/urls.py插入booktest,使主urlconf連接到booktest.urls模塊
url(r'^', include('booktest.urls')),
- 在booktest中的urls.py中添加urlconf
from django.conf.urls import url
from . import views
urlpatterns = [url(r'^$', views.index),url(r'^([0-9]+)/$', views.detail),
]
?
模板
- 模板是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文件,在方法中調用模板
from django.http import HttpResponse
from django.template import RequestContext, loader
from models import BookInfodef index(request):booklist = BookInfo.objects.all()template = loader.get_template('booktest/index.html')context = RequestContext(request, {'booklist': booklist})return HttpResponse(template.render(context))def detail(reqeust, id):book = BookInfo.objects.get(pk=id)template = loader.get_template('booktest/detail.html')context = RequestContext(reqeust, {'book': book})return HttpResponse(template.render(context))
去除模板的硬編碼
- 在index.html模板中,超鏈接是硬編碼的,此時的請求地址為“127.0.0.1/1/”
<a href="{{book.id}}">
- 看如下情況:將urlconf中詳細頁改為如下,鏈接就找不到了
url(r'^book/([0-9]+)/$', views.detail),
- 此時的請求地址應該為“127.0.0.1/book/1/”
- 問題總結:如果在模板中地址硬編碼,將來urlconf修改后,地址將失效
- 解決:使用命名的url設置超鏈接
- 修改test1/urls.py文件,在include中設置namespace
url(r'^admin/', include(admin.site.urls, namespace='booktest')),
- 修改booktest/urls.py文件,設置name
url(r'^book/([0-9]+)/$', views.detail, name="detail"),
- 修改index.html模板中的鏈接
<a href="{%url 'booktest:detail' book.id%}">
Render簡寫
- Django提供了函數Render()簡化視圖調用模板、構造上下文
from django.shortcuts import render
from models import BookInfodef 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})
總結
以上是生活随笔為你收集整理的Django 视图和模板1.4的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: gitflow分支管理模型
- 下一篇: Django 定义模型2.1