booktest/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)
# 评论量
bcomment = models.IntegerField(default=0)
# 删除标记
isDelete = 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',on_delete=models.CASCADE)
# 删除标记
isDelete = models.BooleanField(default=False)
booktest/urls.py
from django.urls import re_path
from .views import *
urlpatterns = [
re_path(r'^index$', index),
re_path(r'^create$', create),
re_path(r'^delete/(\d+)$', delete),
]
booktest/views.py
from django.shortcuts import render,redirect
from django.http import HttpResponseRedirect
from datetime import date
from .models import *
# Create your views here.
def index(request):
# 查询所有图书的信息
books = BookInfo.objects.all()
return render(request,'booktest/index.html',
{'books':books})
def create(request):
# 创建bookinfo实例对象
b = BookInfo()
b.btitle = '鹿鼎记'
b.bpub_date = date(1972,10,10)
b.save()
# 重定向
# return HttpResponseRedirect('/index')
return redirect('/index')
def delete(request,bid):
bookObj = BookInfo.objects.get(id=bid)
bookObj.delete()
# 重定向
return redirect('/index')
templates/booktest/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图书信息</title>
</head>
<body>
<a href="/create">新增</a>
<ul>
{%for i in books%}
<li>{{i.btitle}}---<a href="/delete/{{i.id}}">删除</a></li>
{%endfor%}
</ul>
</body>
</html>
test01/urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("booktest.urls")),
]
test01/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'booktest',
]
ROOT_URLCONF = 'test01.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME':'bj18',
'USER':'root',
'PASSWORD':'12345678',
'HOST':'localhost',
'PROT':3306,
}
}
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/shanghai'