DJango 学习(6)—— Django 数据库连接以及简单的前后端数据交互
pycharm 链接数据库
"""
三个位置
右侧上方 database
左下方 database
配置里面的 plugins 插件搜索
重装 pycharm
pycharm 可以充当很多数据库的客户端
"""
django orm
"""
orm: 对象关系映射
作用:能够让不会sql 语句的小白也可以通过 python 面向对象的代码简单快捷的操作数据库
不足:封装程度太高,有时候 sql 语句的效率偏低 需要自己写 sql 语句
表 ------------ 类
记录 ------------ 对象
某个字段的值 -------- 对象属性
应用 models.py 文件
"""
DATABASES = {
'default': {
'ENGINE': "django.db.backends.mysql",
'NAME': 'test518',
"HOST": "127.0.0.1",
"PORT": 3306,
"USER": "root",
"PASSWORD": ""
}
}
__init__ 文件
import pymysql
pymysql.install_as_MySQLdb()
class User(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
password = models.IntegerField()
1. python manage.py makemigrations 将操作记录记录到小本本上(makemigrations 文件夹)
2. python manage.py migrate 将操作真正同步到数据库中
class User(models.Model):
"""
CharField 必须要有 max_length 参数,不指定会报错
verbase_name 该参数是所有字段都有的,就是用来对字段的解释
"""
id = models.AutoField(primary_key=True, verbose_name="主键")
name = models.CharField(max_length=32,verbose_name="用户名")
password = models.IntegerField(verbose_name="密码")
字段的增删改查
1. 直接在终端内给出 默认值
2. 该字段可以为空,或者直接设置默认值
info = models.CharField(verbose_name="个人简介", max_length=32, null=True)
hobby = models.CharField(max_length=32, verbase_name="爱好", default="study")
直接修改代码,执行数据库迁移的两条命令即可
将对应的字段注释,并执行数据库迁移命令
执行完毕之后,数据消失
"""
在操作 models.py 文件的时候一定要细心
千万不要注释一些字段
执行迁移命令之前最好先检查一下自己写的代码
"""
数据的增删改查
res= models.User.objects.filter(name=username)
user_obj = models.User.objects.all()
return render(request, "usrelist.html", locals())
"""
返回值暂时当作 列表套对象的格式
它也支持索引取值 切片操作 但是不支持负数索引
它也不推荐索引的方式取值
user_obj = models.User.objects.filter(name=username).first()
"""
filter 可以携带多个参数,参数与参数之间默认是 and 关系,可以把 filter 当作 where
res = models.User.objects.create(name=username, password=password)
user_obj = models.User(name=username, password=password)
user_obj.save()
数据的查、改、删
"""
如何告诉后端用户想要编辑哪条数据
将编辑按钮所在的那一行数据的主键值告诉后端
/url/?user_id={{ user_obj.id }}
"""
def useredit(request):
edit_id = request.GET.get("id")
user_obj = models.User.objects.filter(id = edit_id).first()
if request.method == "POST":
name = request.POST.get("username")
password = request.POST.get("password")
user_obj.name = name
user_obj.password = password
user_obj.save()
return redirect("/userlist/")
return render(request, "useredit.html", locals())
跟编辑功能类似
def userdelete(request):
delete_id = request.GET.get("id")
models.User.objects.filter(id=delete_id).delete()
return redirect("/userlist/")
"""
真正的删除功能应该要二次确认,我们这里先不做
删除数据内部其实并不是真正的删除,我们会根据添加一个标识字段来表示当前数据是否被删除,如果数据被删除仅仅只是将字段修改一个状态
"""
name password is_delete
aoteman 123 0
alterman 123 1
代码
urls.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^login/', views.login),
url(r"^regin/", views.regin),
url(r"^userlist/", views.userlist),
url(r"^useredit/", views.useredit),
url(r"^userdelete/", views.userdelete),
]
views.py
from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from app01 import models
def login(request):
if request.method == "POST":
username = request.POST.get("username")
message = models.User.objects.filter(name=username).first()
if message is None:
return HttpResponse("该用户不存在")
password = request.POST.get("password")
user_password = message.possword
if int(password) == user_password:
user_obj = models.User.objects.all()
return redirect('/userlist/', locals())![](https://img-blog.csdnimg.cn/256727490a004e24b28b5164e8714282.gif)
else:
return HttpResponse("密码错误")
return render(request, "login.html")
def regin(request):
if request.method == "POST":
username = request.POST.get("username")
password = request.POST.get("password")
hobby = request.POST.get("hobby")
models.User.objects.create(name=username, possword = password, hobby=hobby)
user_message = models.User.objects.all()
return redirect("/login/")
return render(request, "register.html")
def userlist(request):
user_obj = models.User.objects.all()
return render(request, "usrelist.html", locals())
def useredit(request):
id = request.GET.get("id")
user_obj = models.User.objects.filter(id = id).first()
if request.method == "POST":
username = request.POST.get("username")
password = request.POST.get("password")
models.User.objects.filter(id=id).update(name=username, possword=int(password))
user_obj = models.User.objects.all()
return render(request, "usrelist.html", locals())
return render(request, "useredit.html", locals())
def userdelete(request):
id = request.GET.get('id')
models.User.objects.filter(id=id).delete()
return redirect("/userlist/")
register.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
{% load static %}
<script src="{% static "others/JQuery3.6.0.js" %}"></script>
<link rel="stylesheet" href="{% static 'others/bootstrap-3.4.1-dist/css/bootstrap.min.css' %}">
<script src="{% static 'others/bootstrap-3.4.1-dist/js/bootstrap.min.js' %}"></script>
</head>
<body>
<h1 class="text-center">注册</h1>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<form action="" method="post">
<p>username: <input type="text" name="username" class="form-control"></p>
<p>password: <input type="password" name="password" class="form-control"></p>
<p>
<input type="checkbox" name="hobby" value="111">111
<input type="checkbox" name="hobby" value="222">222
<input type="checkbox" name="hobby" value="333">333
</p>
<input type="submit" class="btn-warning btn-block">
</form>
</div>
</div>
</div>
</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
{% load static %}
<script src="{% static 'others/JQuery3.6.0.js' %}"></script>
<link rel="stylesheet" href="{% static 'others/bootstrap-3.4.1-dist/css/bootstrap.min.css' %}">
<script src="{% static 'others/bootstrap-3.4.1-dist/js/bootstrap.min.js' %}"></script>
</head>
<body>
<h1 class="text-center">登录</h1>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<form action="" method="post">
<p>username: <input type="text" name="username" class="form-control"></p>
<p>password: <input type="password" name="password" class="form-control"></p>
<p>
<input type="checkbox" name="hobby" value="111">111
<input type="checkbox" name="hobby" value="222">222
<input type="checkbox" name="hobby" value="333">333
</p>
<input type="submit" class="btn-success btn-block">
</form>
</div>
</div>
</div>
</body>
</html>
userlist.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
{% load static %}
<script src="{% static "others/JQuery3.6.0.js" %}"></script>
<link rel = "stylesheet" href = "{% static 'others/bootstrap-3.4.1-dist/css/bootstrap.min.css' %}" >
<script src = "{% static 'others/bootstrap-3.4.1-dist/js/bootstrap.min.js' %}" ></script>
</head>
<body>
<div class="container">
<h1 class="text-center">数据展示</h1>
<div class="row">
<div class="col-md-8 col-md-offset-2">
<table class="table table-bordered table-striped table-hover">
<tr>
<th>用户名</th>
<th>密码</th>
<th>介绍</th>
<th>爱好</th>
<th>操作</th>
</tr>
{% for foo in user_obj %}
<tr>
<td>{{ foo.name }}</td>
<td>{{ foo.possword }}</td>
<td>{{ foo.info }}</td>
<td>{{ foo.hobby }}</td>
<td>
<a href="/useredit/?id={{ foo.id }}" class="btn btn-primary btn-xs">编辑</a>
<a href="/userdelete/?id={{ foo.id }}" class="btn btn-danger btn-xs">删除</a>
</td>
</tr>
{% endfor %}
</table>
</div>
</div>
</div>
</body>
</html>
useredit.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
{% load static %}
<script src="{% static "others/JQuery3.6.0.js" %}"></script>
<link rel = "stylesheet" href = "{% static 'others/bootstrap-3.4.1-dist/css/bootstrap.min.css' %}">
<script src = "{% static 'others/bootstrap-3.4.1-dist/js/bootstrap.min.js' %}"></script>
</head>
<body>
<h1 class="text-center">编辑</h1>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<form action="" method="post">
<p>username: <input type="text" name="username" class="form-control" value={{ user_obj.name }}></p>
<p>password: <input type="text" name="password" class="form-control" value={{ user_obj.password }}></p>
<input type="submit" class="btn-warning btn-block">
</form>
</div>
</div>
</div>
</body>
</html>
运行演示