django模板之的html模板中調用對象屬性或對象的方法

環境:依賴最初test2數據庫

           python3版本

           多python版本環境


進入,python3虛擬環境,新建項目test4:

]# cd py3/django-test1/
]# django-admin startproject test4

創建應用bookshop:

]# cd test4
]# python manage.py startapp bookshop

修改settings.py主配置文件:

]# vim test4/settings.py
...
#數據庫爲mysql,使用原來的test2數據庫名稱:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test2',
        'USER': 'root',
        'PASSWORD': 'root',
        'HOST': '192.168.255.70',
        'PORT': '3306',
    }
}
#添加應用:
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'bookshop',
)
#添加模板查找路徑:
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates')],
        ...
]
...

在項目名稱目錄下,添加模板目錄並在其下添加應用的模板目錄:

]# mkdir -p templates/bookshop

在主url路由配置文件中,添加查找應用url的路由:

]# vim test4/settings.py 
...
urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^',include('bookshop.urls',namespace='bookshop')),
]

在應用目錄下創建urls.py文件:

]# vim bookshop/urls.py
from django.conf.urls import url
from .  import views

urlpatterns = [
    url(r'\^$',views.index,name='index'),
]

以上基本配置完成,下面演示在模板中調用對象的方法:

定義模型類:

爲了不用遷移,定義模型類要和test2數據庫結構一樣;

]# vim bookshop/models.py
from django.db import models

class BookInfo(models.Model):
    btitle = models.CharField(max_length=20)
    bpub_date = models.DateTimeField(db_column='pub_date') #定義字段名稱爲pub_date,默認字段名稱就是類屬性,即默認字段名稱爲bpub_date
    bread = models.IntegerField()
    bcommet = models.IntegerField()
    isDelete = models.BooleanField()

    #定義表名
    class Meta():
        db_table = 'bookinfo'
    #如果不寫上面2行,表名默認爲項目名稱.類名稱,即bookshop.bookinfo

class HeroInfo(models.Model):
    hname = models.CharField(max_length=10)
    hgender = models.BooleanField()
    hcontent = models.CharField(max_length=1000)
    isDelete = models.BooleanField()
    book = models.ForeignKey('BookInfo') #定義外鍵,此處引號是否可省略,BookInfo先定義就可省略引號,如果後定義則需要使用引號,使用引號絕對沒錯;在表中字段自動變爲book_id
    
    def showname(self):
        return self.hname

定義視圖:

]# vim bookshop/views.py
from django.shortcuts import render
from .models import *
#from models import * #在python2寫法


def index(request): #必須接收一個參數
    hero = HeroInfo.objects.get(pk=1) #查詢主鍵(pk)=1的條目
    context = {'hero':hero} #必須爲字典格式
    return render(request,'bookshop/index.html',context)

定義index.html模板文件:

]# vim templates/bookshop/index.html
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
</head>
<body>
{{ hero.hname }}<br><!--調用對象的屬性-->
{{hero.showname}}<!--調用對象的方法,但不能給方法傳遞參數-->

<!--註釋
#點號解析順序:
#1.先把hero作爲字典,hname爲鍵查找
#2.再把hero作爲對象,hname爲屬性或方法查找
#3.最後把hero作爲列表,hname爲索引查找
-->

</body>
</html>

啓動web服務:

]# python manage.py runserver 192.168.255.70:8000
報錯:Error loading MySQLdb module: No module named 'MySQLdb'

解決:由於在python3版本上使用pymysql庫,沒有MySQLdb庫,則需要配置;


]# vim test4/__init__.py
import pymysql
pymysql.install_as_MySQLdb()

再次啓動web服務成功;瀏覽器訪問:http://192.168.255.70:8000/

QQ截圖20181130004037.png

完成驗收在html模板文件中調用對象的屬性和對象的方法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章