環境:依賴最初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/

完成驗收在html模板文件中調用對象的屬性和對象的方法。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。