django創(chuàng)建項目案例1詳細(xì)展示續(xù)05

  • 接著上一個django創(chuàng)建項目案例1的04繼續(xù)如下:

定義show.html模板目錄如下:

[圖片上傳失敗...(image-3b999b-1531897111035)]

show.html代碼如下:

  • 在模板中訪問對象成員時,都以屬性的方式訪問,即方法也不能加括號
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<ul>
    {%for hero in list%}
    <li>{{hero.hname}}</li>
    {%endfor%}
</ul>
</body>
</html>

在hero info里隨意添加內(nèi)容如圖:

[圖片上傳失敗...(image-f8d008-1531897111035)]
[圖片上傳失敗...(image-39185e-1531897111035)]

使用模板

  • 編輯views.py文件,在方法中調(diào)用模板代碼如下:
#coding:utf-8
from django.shortcuts import render
from django.http import *
from .models import *
# from django.template import RequestContext,loader

# Create your views here.
def index(request):
    # temp = loader.get_template('booktest/index.html')
    # return HttpResponse(temp.render())
    bookList=BookInfo.objects.all()
    context={'list':bookList}
    return render(request,'booktest/index.html',context)

def show(request,id):
    book=BookInfo.objects.get(pk=id)
    herolist=book.heroinfo_set.all()
    context={'list':herolist}
    return render(request,'booktest/show.html',context)

知識點介紹

去除模板的硬編碼

  • 在index.html模板中,超鏈接是硬編碼的,此時的請求地址為“127.0.0.1/1/”
<a href="{{book.id}}">
  • 看如下情況:將urlconf中詳細(xì)頁改為如下,鏈接就找不到了
url(r'^book/([0-9]+)/$', views.detail),
  • 此時的請求地址應(yīng)該為“127.0.0.1/book/1/”
  • 問題總結(jié):如果在模板中地址硬編碼,將來urlconf修改后,地址將失效
  • 解決:使用命名的url設(shè)置超鏈接
  • 修改test1/urls.py文件,在include中設(shè)置namespace
url(r'^admin/', include(admin.site.urls, namespace='booktest')),
  • 修改booktest/urls.py文件,設(shè)置name
url(r'^book/([0-9]+)/$', views.detail, name="detail"),

  • 修改index.html模板中的鏈接
<a href="{%url 'booktest:detail' book.id%}">

Render簡寫

  • Django提供了函數(shù)Render()簡化視圖調(diào)用模板、構(gòu)造上下文
  • 修改booktest目錄下的urls.py文件代碼目錄如下:
    [圖片上傳失敗...(image-995f40-1531897111035)]
    代碼如下:
#coding:utf-8
from django.conf.urls import url
from . import views


urlpatterns=[
    url(r'^$',views.index),
    url(r'^(\d+)$',views.show)
]
  • 然后運行python manage.py runserver

  • 效果圖如下:
    [圖片上傳失敗...(image-62414-1531897111035)]
    [圖片上傳失敗...(image-c715a3-1531897111035)]
    [圖片上傳失敗...(image-8a6164-1531897111035)]

詳細(xì)瀏覽我的博客(https://yq.aliyun.com/users/article?spm=a2c4e.11153940.headeruserinfo.3.24a6291aUNlJjF&do=login)
阿里云大禮包(https://promotion.aliyun.com/ntms/yunparter/invite.html?userCode=66enueqz)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容