以下内容需要掌握:
Python3 以及前端:HTML,CSS,jQuery,BootStrap,Django,JavaScript
开启Django新项目:
1,settings.py
数据库选择:
①sqlite3(Django自带的数据库:文件式数据库):我们这里用sqlite3,下面MySQL配置仅做了解
②MySQL: 配置:
__init__.py:(对应应用文件夹下和urls.py同一个文件夹)
import pymysql
pymysql.install_as_MySQLdb()
------------------------------
settings.py:
DATABASES = {
‘default‘: {
‘ENGINE‘: ‘django.db.backends.mysql‘,
‘NAME‘: ‘------输入数据库名---------‘,
‘USER‘: ‘------输入数据库用户名root/其它----------‘,
‘PASSWORD‘: ‘-----输入数据库密码------‘,
‘HOST‘: ‘127.0.0.1‘,
‘PORT‘: ‘3306‘,
}
}
2,建一个static文件夹:(项目名---新建--python package)
BootStrap文件夹
jQuery.3.3.1.js
自定义CSS
settings.py配置:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
os.path.join(BASE_DIR, "recommend", "static"), # 不加这句有可能出现页面渲染不了bootstrap的情况
]
3,让控制台显示SQL查询语句
settings.py配置:
LOGGING = {
‘version‘: 1,
‘disable_existing_loggers‘: False,
‘handlers‘: {
‘console‘:{
‘level‘:‘DEBUG‘,
‘class‘:‘logging.StreamHandler‘,
},
},
‘loggers‘: {
‘django.db.backends‘: {
‘handlers‘: [‘console‘],
‘propagate‘: True,
‘level‘:‘DEBUG‘,
},
}
}
4,templates目录下放网页
books.html 显示所有书籍
//jQuery.js引入到HTML:
<script src="/static/jQuery.3.3.1.js"></script>
//BootStrap.css引入到HTML:
<link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css">
//-------------------------------------------------------
//书籍列表
//添加书籍
//表格:
//ID 书名 价格 出版日期 出版商 操 作
//-------------------------------------------------------
<h3>书籍列表</h3>
<div class="row">
<div class="col-md-8 col-md-offset-2">
<a href="/books/add/" class="btn btn-primary"> 添加书籍</a>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>ID</th>
<th>书籍名称</th>
<th>价格</th>
<th>出版社</th>
<th>出版日期</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for book in queryset %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ book.title }}</td>
<td>{{ book.price }}</td>
<td>{{ book.publish }}</td>
<td>{{ book.pub_date|date:"Y/m/d" }}</td>
<td>
<a href="/books/delete/{{ book.nid }}">删除</a>
<a href="/books/edit/{{ book.nid }}">编辑</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<script>
$("h3").click(function () {-------------------jQuery的知识
$(this).css("color","red")
})
</script>
addbook.html 添加书籍
jQuery.js引入到HTML:
<script src="/static/jQuery.3.3.1.js"></script>
BootStrap.css引入到HTML:
<link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css">
----------------------------
书名:input
价格:input
出版日期:input
出版商:input
Submit提交
-----------------------------------
<h3>添加书籍</h3>
<div class="row">
<div class="col-md-4 col-md-offset-3">
<form action="/books/add/" method="post">
{% csrf_token %}
<div class="form-group">
<label for="title">书籍名称</label>
<input class="form-control" type="text" id="title" placeholder="名称" name="title">
</div>
<div class="form-group">
<label for="price"> 价格</label>
<input class="form-control" type="text" id="price" placeholder="价格" name="price">
</div>
<div class="form-group">
<label for="publish">出版社</label>
<input class="form-control" type="text" id="publish" placeholder="出版社" name="publish">
</div>
<div class="form-group">
<label for="pub_date">出版日期</label>
<input class="form-control" type="date" id="pub_date" placeholder="出版日期" name="pub_date">
</div>
<input type="submit"value="submit" class="btn btn-default pull-right">
</form>
</div>
</div>
editbook.html 编辑书籍
//jQuery.js引入到HTML:
<script src="/static/jQuery.3.3.1.js"></script>
//BootStrap.css引入到HTML:
<link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css">
-----------------------
编辑书籍
书名:input value=从数据库获取当前选择的ID对应的数据显示
价格:input value=从数据库获取当前选择的ID对应的数据显示
出版日期:input value=从数据库获取当前选择的ID对应的数据显示
出版商:input value=从数据库获取当前选择的ID对应的数据显示
Submit
----------------------
<h3>编辑书籍</h3>
<div class="row">
<div class="col-md-4 col-md-offset-3">
<form action="" method="post">
{% csrf_token %}
<div class="form-group">
<label for="title">书籍名称</label>
<input class="form-control" type="text" id="title" placeholder="名称" name="title" value="{{ edit_book.title }}">
</div>
<div class="form-group">
<label for="price"> 价格</label>
<input class="form-control" type="text" id="price" placeholder="价格" name="price" value="{{ edit_book.price }}">
</div>
<div class="form-group">
<label for="publish">出版社</label>
<input class="form-control" type="text" id="publish" placeholder="出版社" name="publish" value="{{ edit_book.publish }}">
</div>
<div class="form-group">
<label for="pub_date">出版日期</label>
<input class="form-control" type="date" id="pub_date" placeholder="出版日期" name="pub_date" value="{{ edit_book.pub_date|date:‘Y-m-d‘ }}">
</div>
<input type="submit"value="submit" class="btn btn-default pull-right">
</form>
</div>
</div>
5,models.py
class Book(models.Model): # -------继承模型类
id = models.AutoField(primary_key=True) # --------自增(主键)
title = models.CharField(max_length=32) # --------字符串(长度32位)
price = models.DecimalField(max_digits=5,decimal_places=2) # -----最大位数,浮点位数
publish = models.CharField(max_length=32)
pub_date = models.DateTimeField()
class Meta: # ------告诉解析器自己定义数据表名(否则 app01Book)
db_table=‘book‘
6,数据库迁移
Tools(工具栏):
run manage.py Task...
>>>>>>>makemigrations
>>>>>>>migrate
完了后生成了db.sqlite3文件:
pycharm右边database:(sqlite3首次使用需下载,弹出框有,完后,左边项目目录下db.sqlite3双击)
点开右边database:book可以看到加入数据库的表格字段
7,urls.py
..............import re_path
from book import views
urlpatterns=[
...........
path(‘books‘,views.books)
path(‘books/add/‘, views.addbook)
re_path(‘books/delete/(\d+)‘, views.delbook)
re_path(r‘^books/edit/(\d+)$‘, views.editbook)
]
8,views.py
def books(request):
queryset = Book.objects.all()
return render(request,‘books.html‘,{‘queryset‘:queryset})
def addbook(request):
# 方式1:
if request.method==‘POST‘:
# title=request.POST.get(‘title‘)
# ...
# book=models.Book.objects.create(titles=title,price=price,publish=publish,pub_date=pub_date)
# 方式2:(推荐)
data=request.POST.dict() #-----------Querydict生成字典
data.pop(‘csrfmiddlewaretoken‘)
book=models.Book.objects.create(**data) #-----聚合
return redirect(‘/books/‘) #-----------重定向到books
else
return return render(request,‘addbook.html‘)
def delbook(request,del_id):
models.Book.objects.filter(nid=del_id).delete()
return redirect("/books/")
def editbook(request,edie_id):
if request.method=="GET":
edit_book=models.Book.objects.filter(nid=edit_book_id).first()
return render(request,"editbook.html",{"edit_book":edit_book})
else:
title = request.POST.get("title")
price = request.POST.get("price")
publish = request.POST.get("publish")
pub_date = request.POST.get("pub_date")
models.Book.objects.filter(nid=edit_book_id).update(title=title,price=price,publish=publish,pub_date=pub_date)
return redirect("/books/")
启动项目:
浏览器输入:
http://127.0.0.1:8000/books
原文地址:https://www.cnblogs.com/searchforyou/p/10259957.html