一、初始化框架相关数据库
Django框架默认内置了一些app,这些app是需要数据库支撑的,我们可以先在helloWorld\settings.py中进行数据库配置(这里使用默认配置):
然后再执行下面的命令来生成相关的数据库表
python manage.py migrate
输出内容如下图:
二、初始化app及models.py
2.1、新建一个app(ch3)并做好相关配置,然后我们修改ch3\models.py(这部分的内容可以直接参考Django官网的模型部分)。
ch3\models.py内容如下:
import datetime
from django.db import models
from django.utils import timezone
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField("date published")
def __str__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
2.2、执行下面的指令生成迁移文件:
python manage.py makemigrations ch3
迁移文件在ch3目录下的migrations目录,如图:
文件具体内容请自行查看。
2.3、查看SQL,请执行下面的命令
python manage.py sqlmigrate ch3 0001
命令行显示如下:
BEGIN;
--
-- Create model Question
--
CREATE TABLE "ch3_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);
--
-- Create model Choice
--
CREATE TABLE "ch3_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" bigint NOT NULL REFERENCES "ch3_question" ("id") DEFERRABLE INITIALLY DEFERRED);
CREATE INDEX "ch3_choice_question_id_037088df" ON "ch3_choice" ("question_id");
COMMIT;
2.4、生成相应的数据库表
再次执行:
python manage.py migrate
三、增删改查
这里我们直接上代码
1、定义路由(ch3\urls.py)
from django.urls import path
from . import views
app_name = "ch3"
urlpatterns = [
path("", views.index, name="index"),
path("add_new", views.add_new, name="add_new"),
path("do_add_new", views.do_add_new, name="do_add_new"),
path("do_clear", views.do_clear, name="do_clear"),
path("go_edit", views.go_edit, name="go_edit"),
path("do_edit", views.do_edit, name="do_edit"),
path("do_delete", views.do_delete, name="do_delete"),
]
2、路由函数(ch3\views.py)
from django.shortcuts import render, reverse, redirect
from django.http import HttpRequest, HttpResponse, HttpResponseServerError
from django.core.paginator import Paginator
from .models import Question, Choice
from django.utils import timezone
def index(request):
page_no = request.GET.get('page', default=1)
page_size = request.GET.get('page_size', default=5)
questions = Question.objects.all().order_by('-pub_date')
paginator = Paginator(questions, page_size)
page_obj = paginator.get_page(page_no)
return render(request, 'ch3/index.html', {'page_obj': page_obj, 'total': paginator.count})
def add_new(request):
return render(request, 'ch3/add_new.html')
def do_add_new(request: HttpRequest):
question_text = request.POST.get('question_text', default='')
if question_text == '':
return HttpResponseServerError("问题内容不能为空!")
q = Question(question_text=question_text, pub_date=timezone.now())
q.save()
return redirect(reverse('ch3:index'))
def do_clear(request: HttpRequest):
Question.objects.all().delete()
return redirect(reverse('ch3:index'))
def go_edit(request: HttpRequest):
obj_id = request.GET.get('id', default=0)
question = Question.objects.get(id=obj_id)
return render(request, 'ch3/go_edit.html', {"question": question})
def do_edit(request: HttpRequest):
obj_id = request.POST.get('id')
pub_date = request.POST.get('pub_date')
question_text = request.POST.get('question_text', default='')
if question_text == '':
return HttpResponseServerError("问题内容不能为空!")
q = Question(id=obj_id, question_text=question_text, pub_date=pub_date)
q.save()
return redirect(reverse('ch3:index'))
def do_delete(request: HttpRequest):
obj_id = request.GET.get('id', default=0)
Question.objects.filter(id=obj_id).delete()
return redirect(reverse('ch3:index'))
3、视图代码
3.1、ch3\index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ch3</title>
<style>
#container{
width: 90%;
margin: 0 auto;
}
table{
width: 100%;
border:1px solid blue;
border-collapse: collapse;
}
th,td{
border:1px solid blue;
padding: 5px;
}
.center{
text-align: center;
}
</style>
<script type="text/javascript">
function add_new(){
window.location.href="{% url 'ch3:add_new' %}"
}
function do_clear(){
window.location.href="{% url 'ch3:do_clear' %}"
}
function go_edit(id){
window.location.href="{% url 'ch3:go_edit' %}?id="+id
}
function do_delete(id){
window.location.href="{% url 'ch3:do_delete' %}?id="+id
}
</script>
</head>
<body>
<div id="container">
<h1>ch3</h1>
<a href="{% url 'index' %}">返回主页</a>
<div style="float: right;margin: 10px;">
<button onclick="add_new()">新增记录</button>
<button onclick="do_clear()">清空记录</button>
</div>
<table>
<thead>
<tr>
<th style="width: 15%;">ID</th>
<th style="width: 50%;">问题</th>
<th style="width: 20%;">发布时间</th>
<th style="width: 15%;">操作</th>
</tr>
</thead>
<tbody>
{% if total > 0 %}
{% for item in page_obj %}
<tr>
<td>{{ item.id }}</td>
<td>{{ item.question_text }}</td>
<td>{{ item.pub_date|date:"Y-m-d H:i:s" }}</td>
<td class="center">
<button onclick="go_edit({{ item.id }})">编辑</button>
<button onclick="do_delete({{ item.id }})">删除</button>
</td>
</tr>
{% endfor %}
{% else %}
<tr>
<td style="color: red;text-align: center;" colspan="4">没有可以显示的数据!</td>
</tr>
{% endif %}
</tbody>
</table>
<div class="pagination">
<span class="step-links">
{% if page_obj.has_previous %}
<a href="?page=1">« 首页</a>
<a href="?page={{ page_obj.previous_page_number }}">‹ 上一页</a>
{% endif %}
<span class="current">
第 {{ page_obj.number }} 页 / 共 {{ page_obj.paginator.num_pages }} 页
</span>
{% if page_obj.has_next %}
<a href="?page={{ page_obj.next_page_number }}">下一页 ›</a>
<a href="?page={{ page_obj.paginator.num_pages }}">尾页 »</a>
{% endif %}
</span>
</div>
</div>
</body>
</html>
3.2、ch3\add_new.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>add_new</title>
</head>
<body>
<h1>add_new</h1>
<a href="{% url 'ch3:index' %}">返回ch3</a>
<form method="post" action="/ch3/do_add_new">
{% csrf_token %}
<label>问题内容:</label>
<input type="text" name="question_text" autocomplete="off"/>
<button type="submit">提交</button>
</form>
</body>
</html>
3.3、ch3\go_edit.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>add_new</title>
</head>
<body>
<h1>add_new</h1>
<a href="{% url 'ch3:index' %}">返回ch3</a>
<form method="post" action="/ch3/do_edit">
{% csrf_token %}
<input type="hidden" name="id" value="{{ question.id }}"/>
<input type="hidden" name="pub_date" value="{{ question.pub_date|date:"Y-m-d H:i:s" }}"/>
<label>问题内容:</label>
<input type="text" name="question_text" autocomplete="off" value="{{ question.question_text }}"/>
<button type="submit">提交</button>
</form>
</body>
</html>