這篇文章主要介紹了Django框架搭建的簡易圖書信息網站案例,結合具體實例形式分析了基於Django框架實現圖書信息管理網站的具體步驟、相關實現技巧與操作注意事項,需要的朋友可以參考下
本文實例講述了Django框架搭建的簡易圖書信息網站。分享給大家供大家參考,具體如下:
創建Django項目,將數據庫改爲mysql,修改項目的urls.py文件
創建一個新應用,在應用裏創建urls.py文件。
在應用的models.py裏建表
from django.db import models # Create your models here. #一類 class BookInfo(models.Model): btitle=models.CharField(max_length=20)#圖書名稱 bpub_date=models.DateField()#出版日期 bread=models.IntegerField(default=0)#閱讀量,默認爲0 bcomment=models.IntegerField(default=0)#評論量 isDlete=models.BooleanField(default=False)#邏輯刪除,默認不刪除 #多類 class HeroInfo(models.Model): hname=models.CharField(max_length=20) hgender=models.BooleanField(default=False) hcomment=models.CharField(max_length=200) #定義一個關係屬性 hbook=models.ForeignKey('BookInfo') isDlete = models.BooleanField(default=False) # 邏輯刪除,默認不刪除
首頁index.html查詢所有圖書信息,在views.py裏完善index函數。
def index(request): # 1.查詢出所有圖書的信息 books = BookInfo.objects.all() # 2.使用模板 return render(request, 'booktest/index.html', {'books': books})
在template文件夾下的booketest文件夾下新建index.html文件。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>圖書信息</title> </head> <body> <a href="/create" rel="external nofollow" >新增</a> <ul> {% for book in books %} <li><a href="/books{{ book.id }}" rel="external nofollow" >{{ book.btitle }}</a><a href="/delete{{ book.id }}" rel="external nofollow" >_刪除</a></li> {% endfor %} </ul> </body> </html>
index.html裏有一個create新增按鈕,去view.py裏添加create處理函數
def create(request): '''新增一本圖書''' # 1.創建一個bookinfo對象 b = BookInfo() b.btitle = '流星蝴蝶劍' b.bpub_date = date(1990, 1, 1) # 2.保存進數據庫 b.save() # 3.返回應答 # return HttpResponse('ok') # 讓瀏覽器返回首頁 return HttpResponseRedirect('/index')
數據庫裏添加上之後,重定向到首頁index。
應用的urls.py文件裏要寫url(r'^create$',views.create)
,才能正確的跳轉到create處理函數。
一個顯示書里人物的details.html,從index.html用book.id去尋找書的數據。
去views.py寫details處理函數
def details(request,bid): book=BookInfo.objects.get(id=bid) heros=book.heroinfo_set.all() return render(request,'booktest/details.html',{'book':book,'heros':heros})
新建details.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>{{book.btitle}}</h1> 英雄信息: <br/> <ul> {% for hero in heros %} <li>{{hero.hname}}--{{hero.hcomment}}</li> {% empty %} 沒有英雄信息 {% endfor %} </ul> </body> </html>
去應用的urls.py裏把url地址和視圖處理函數對應上
url(r'^books(\d+)$',views.details)
這裏的(\d+)是需要傳參到details視圖處理函數。
github:https://github.com/zhangyuespec/Django
希望本文所述對大家基於Django框架的Python程序設計有所幫助。