创建djiango项目的详细步骤
1:进入项目目录执行
django-admin startproject mysite
2: 进入mysite目录,在下面创建app应用bookstore
django-admin startapp bookstore
3: 用pycharm软件打开mysite文件夹
4: 找到mysite下面的settings.py文件夹设置
1):找到"ALLOWED_HOSTS= [] " 将其改为 ALLOWED_HOSTS = [“*”]
2):找到"INSTALLED_APPS = " 在里面安装应用 “bookstore”
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bookstore',
]
3):找到"MIDDLEWARE = " 暂时将跨域中间件关闭 #django.middleware.csrf.CsrfViewMiddleware’,
4):进入数据库 创建django 项目需要链接的数据库
mysql -uroot -py
create database mysite_db default charset utf8 collate utf8_general_ci;
5):找到"DATABASES = " 修改数据库引擎
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mysite_db',
'USER': "root",
'PASSWORD': '123456',
'PORT': '3306',
'HOST': '127.0.0.1',
}
}
6): 将以下内容改为:
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Shanghai'
5:找到mysite文件夹下的__init__.py文件 在里面添加对mysql数据库的支持
import pymysql
pymysql.install_as_MySQLdb()
6:在bookstore文件夹中找到models.py文件,在这之中创建类用来操作数据库 ORM模型
1):编写Book类
from django.db import models
class Book(models.Model): #这里的Book相当于mysql数据库中的Book数据表
#这里的title ,price , market_price, publisher, pub_date 相当于数据表中的字段
title = models.CharField(max_length=30,
verbose_name="书名")
price = models.DecimalField(max_digits=7,
decimal_places=2,
verbose_name="出厂价")
market_price = models.DecimalField(max_digits=7,
decimal_places=2,
verbose_name="市场价")
publisher = models.CharField(max_length=30,
verbose_name="出版社")
pub_date = models.DateTimeField(auto_now_add=True)
2): 在项目目录下执行命令同步数据库
python3.9 manage.py makemigrations
python3.9 manage.py migrate
7: 在项目根目录下创建templates 文件夹 然后创建bookstore文件夹 用来存放html文件和模板
1):编写add_book.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加新书</title>
<style>
#addBook{
width: 500px;
height: 400px;
background-color: #eee;
color: #888;
border: 0px solid red;
}
#addBook div{
width: 100%;
height: 60px;
border: 0px solid blue;
}
#addBook h2{
display: inline-block;
width: 100%
height: 80px;
}
#addBook .submit{
display: inline-block;
padding: 10px 10px;
margin-top: 20px;
margin_left: 20px;
}
</style>
</head>
<body>
<form action="/bookstore/add_book" method="post">
<div id="addBook">
<h2>添加图书</h2>
<div class="title">
<label>请输入书名:</label>
<input type="text" name="title">
</div>
<div class="price">
<label>请输入定价:</label>
<input type="text" name="price">
</div>
<div class="publisher">
<label>请输入出版社:</label>
<input type="text" name="publisher">
</div>
<div class="marketPrice">
<label>请输入市场价:</label>
<input type="text" name="marketPrice">
</div>
<input type="submit" value="添加图书">
</div>
</form>
</body>
</html>
2): 编写 show.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图书查询系统</title>
<style>
a{
text-decoration: none;
color: #000;
}
#selectBook{
width: 840px;
}
#selectBook .op{
width: 100%;
height: 40px;
border: 1px solid red;
overflow: hidden;
}
#selectBook .op div{
width: 278px;
height: 38px;
border: 1px solid red;
float: left;
text-align: center;
padding-top: 10px;
background-color: #ccc;
color: #888;
}
#showTable{
width: 840px;
margin-top: 10px;
}
#showTable>tr{
width: 100%;
}
#showTable tr>th{
width: 131px;
height: 30px;
text-align: center;
border: 1px solid #ccc;
background-color: rgb(21, 159, 132);
color: #000;
}
#showTable tr>td{
width: 108px;
height: 30px;
border: 1px solid #ccc;
text-align: center;
background-color: rgb(21, 159, 132);
color: #000;
}
</style>
</head>
<body>
<div id="selectBook">
<div class="op">
<div>
<input type="button" id="add" name="add" value="添加图书" onclick="location.href='http://192.168.0.240:5000/bookstore/add_book'">
</div>
<div>
<input type="button" id="remove" name="remove" value="删除图书">
</div>
<div>
<input type="button" id="update" name="update" value="修改图书">
</div>
</div>
<div id="showTable">
<table>
<tr>
<th>id</th>
<th>书名</th>
<th>出版社</th>
<th>定价</th>
<th>市场价</th>
<th>删除</th>
<th>更改</th>
</tr>
{% for abook in books %}
<tr>
<td>{{ abook.id }}</td>
<td>{{ abook.title }}</td>
<td>{{ abook.publisher }}</td>
<td>{{ abook.price }}</td>
<td>{{ abook.market_price }}</td>
<td><a href='http://192.168.0.240/bookstore/remove/{{ abook.id }}'>删除</a></td>
<td><a href='http://192.168.0.240/bookstore/mod/{{ abook.id }}'>更改</a></td>
</tr>
{% endfor %}
</table>
</div>
</body>
</html>
8: 在bookstore文件下找到views.py文件,创建add.view函数
from django.shortcuts import render
from django.http import HttpResponse
from . import models
# Create your views here.
def add_book_view(request):
#调用models中Book生成对象,用Book 中的objects create 方法来操作对象
try:
abook = models.Book.objects.create(
title="python",
price=88.88,
market_price=99.99,
publisher="黄编市场"
)
return HttpResponse("图书添加成功!")
except Exception as err:
return HttpResponse("图书添加失败!")
为了方便操作我们编写图形化界面来完成对数据库的增删改查:
if request.method == "GET":
return render(request, "bookstore/add_book.html")
elif request.method == "POST":
title = request.POST.get("title")
price = request.POST.get("price")
market_price = request.POST.get("market_price")
publisher = request.POST.get("publisher")
try:
abook = models.Book.objects.create(
title = title,
price = price,
market_price = market_price,
publisher = publisher
)
return HttpResponse("图书添加!")
except:
return HttpResponse("图书添加失败!")
9: 在bookstore文件找到views.py编写show.view函数
def show_view(request):
books = models.Book.objects.all()
return render(request, "bookstore/show.html", locals())
10:添加分布式路由:
1): 在bookstore文件夹中创建urls.py文件
from django.urls import path
from django.urls import re_path
from . import views
urlpatterns = [
path(r'add_book', views.add_book_view),
path(r'show', views.show_view),
]
2)在mysite文件夹中找到urls.py文件创建路由:
from django.contrib import admin
from django.urls import path
from django.urls import re_path
from django.urls import include
import bookstore
urlpatterns = [
path('admin/', admin.site.urls),
path(r'bookstore/', include("bookstore.urls"))
]