首页 > 编程 > Python > 正文

Django框架搭建的简易图书信息网站案例

2019-11-25 12:51:12
字体:
来源:转载
供稿:网友

本文实例讲述了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程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表