mysql -u root -p
password:(输入密码)
create database stu DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
Django连接数据库:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'stu',
'USER': 'root',
'PASSWORD': '123456',
'HOST': 'localhost',
'PORT': 3306,
}
}
from django.db import models
class StuInfo(models.Model):
name = models.CharField(max_length=32)
password = models.CharField(max_length=64)
age = models.IntegerField()
此操作相当于MySQL中的
create tables app01_stuinfo{
id bigint auto_increment primary key,
name varchar(32),
password varchar(64),
age int
}
python manage.py makemigrations
python manage.py migrate
注:因为Django本身默认提供了其他的APP,并且依赖于数据库的一些表,所以也同时生成了默认的APP的表。
此时,一个简单的数据库就创建完成了。
(2)直接退出,为该属性设置一个默认值
添加一个页面
path('info/', views.info),
添加函数(若添加元组成功则info页面显示成功)
from app01.models import StuInfo
def info(request):
StuInfo.objects.create(name="Alex", password="123321", age=19, classroom=3)
StuInfo.objects.create(name="Bob", password="123421", age=16, classroom=6)
StuInfo.objects.create(name="John", password="1541", age=17, classroom=8)
return HttpResponse("成功!")
1,按条件删除(先筛选,再删除)
StuInfo.objects.filter(id=2).delete()
StuInfo.objects.all(id=2).delete()
data_list = StuInfo.objects.all()
print(data_list)
1,更新所有数据
StuInfo.objects.all().update(classroom=1)
2,按条件更新数据
StuInfo.objects.filter(name="John").update(classroom=10)
infolist.html
Title
info列表
ID
姓名
年龄
班级
{% for obj in data_list %}
{{ obj.id }}
{{ obj.name }}
{{ obj.age }}
{{ obj.classroom }}
{% endfor %}
views.py
from django.shortcuts import render, HttpResponse, redirect
from app01.models import StuInfo
def infolist(request):
data_list = StuInfo.objects.all()
return render(request, "infolist.html", {"data_list": data_list})
models.py
path('infolist/', views.infolist),
models.py
from django.db import models
class StuInfo(models.Model):
name = models.CharField(max_length=32)
password = models.CharField(max_length=64)
age = models.IntegerField()
classroom = models.IntegerField()
urls.py
path('infoadd/', views.infoadd),
infoadd.html 制做前端页面,并将输入的内容发送到后端 。 {% csrf_token %}
(不要忘记!)
Title
添加信息
views.py 获取数据并添加用户写入数据库成功后 跳转到用户信息页面
def infoadd(request):
if request.method == "GET":
return render(request, "infoadd.html")
user = request.POST.get("user")
age = request.POST.get("age")
password = request.POST.get("password")
classroom = request.POST.get("classroom")
StuInfo.objects.create(name=user, age=age, password=password, classroom=classroom)
return redirect("/infolist")
添加url
path('delete/', views.delete),
添加函数
def delete(request):
nid = request.GET.get("nid")
StuInfo.objects.filter(id=nid).delete()
return HttpResponse("删除成功!")
更改infolist.html,增加删除栏
Title
info列表
ID
姓名
年龄
班级
操作
{% for obj in data_list %}
{{ obj.id }}
{{ obj.name }}
{{ obj.age }}
{{ obj.classroom }}
删除
{% endfor %}