1.创建项目
1. 创建项目
用pycharm 选择对应的编译器,输入对应的文件名,点击创建项目。删除默认外层生成的template和DIRS 配置项:
2. 创建App
创建appo1的命令:
python manage.py startapp app01
如果使用pycharm>tool>manage.py task:
manage.py@day16 > startapp app01
生成APP之后,在setting的INSTALLED_APP中注册:
INSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','app01.apps.App01Config'
]
3.用Django的方式创建表结构
进入app01>model.py中,写表结构:
from django.db import modelsclass Department(models.Model):"""部门表"""id = models.BigAutoField(verbose_name='id,自增', primary_key=True) # bigint类型# id = models.AutoField(verbose_name='id,自增',primary_key=True)#int类型title = models.CharField(verbose_name='标题', max_length=32)class UserInfo(models.Model):"""员工表"""name = models.CharField(verbose_name="姓名", max_length=16)password = models.CharField(verbose_name="密码", max_length=64)age = models.IntegerField(verbose_name='年龄')account = models.DecimalField(verbose_name='账户余额', max_length=10, decimal_places=2, default=0)creat_time = models.DateTimeField(verbose_name='入职时间')# 无约束depart_id = models.BigIntegerField(verbose_name='部门ID')# 1.有约束# - to:表示与哪张表关联# - to_field:与这张表的哪一列关联# 2.django:自动加# - 写的depart,但实际数据库字段为depart_id# 3.如果部门表被删除# - 3.1级联删除depart = models.ForeignKey(to='Department', to_field='id', on_delete=models.CASCADE)# - 3.2 置空depart = models.ForeignKey(to='Department', to_field='id', blank=True, null=True ,on_delete=models.SET_NULL)
4.生成数据库的表
格式:mysql [-h 主机名] -u 用户名 -p密码 [-P端口号] [-D数据库名]
参数选项:
[-h主机名或ip地址]或者[–host=主机名ip地址]:指定登录的主机名;
[-u用户名]或者[–user=用户名]:指定用户登录的用户名;
[-p密码(p小写)]或者[–password=密码]:输入登录密码;
[-P端口号(P大写)]或者[–port=端口号]:指定登录的MySQL的端口号;
[-D数据库名]或者[–database=数据库名]:指定登录的数据库名称;
登录本地数据库,只需要指定用户名(-u)和密码(-p)即可,不需要指定主机名(-h)
create database day16 DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
查看所有数据库:
show databases;
在setting.py中修改数据库配置:
DATABASES = {'default': {'ENGINE': 'django.db.backends.mysql','NAME': 'django', # 数据库名字'USER': 'root','PASSWORD': '123456','HOST': '127.0.0.1', # 要连接哪台机器上的MySQL'PORT': '3306' # 端口号}
}
python manage.py makemigrations
python manage.py migrate
查看生成的表:
use 数据名;
show tables;
desc app01_department;
5.部门管理
目前只是体验,用最原始的方法做的
Django中提供Form和ModelForm组件,非常方便。
5.1 部分列表
from django.db import modelsclass Department(models.Model):"""部门表"""id = models.BigAutoField(verbose_name='id,自增', primary_key=True) # bigint类型# id = models.AutoField(verbose_name='id,自增',primary_key=True)#int类型title = models.CharField(verbose_name='标题', max_length=32)class UserInfo(models.Model):"""员工表"""name = models.CharField(verbose_name="姓名", max_length=16)password = models.CharField(verbose_name="密码", max_length=64)age = models.IntegerField(verbose_name='年龄')account = models.DecimalField(verbose_name='账户余额', max_digits=10, decimal_places=2, default=0)creat_time = models.DateTimeField(verbose_name='入职时间')# 无约束# depart_id = models.BigIntegerField(verbose_name='部门ID')# 1.有约束# - to:表示与哪张表关联# - to_field:与这张表的哪一列关联# 2.django:自动加# - 写的depart,但实际数据库字段为depart_id# 3.如果部门表被删除 # - 3.1级联删除depart = models.ForeignKey(to='Department', to_field='id', on_delete=models.CASCADE)# - 3.2 置空depart = models.ForeignKey(to='Department', to_field='id', blank=True, null=True, on_delete=models.SET_NULL)# 4.Django中做的约束:gender_choices = ((0, '女'),(1, '女'))gender = models.SmallIntegerField(verbose_name='性别,男1,女0', choices=gender_choices)
2.模板的继承
通过将共用的部分做成一个模板,然后在不同的位置插入插槽,最终通过继承共用部分,重写差异化部分,达到代码复用。
在复用的代码部分,加入插槽,文件命名为layout.html:
<div class="content">{% block css %}{% endblock %}{% block content %}{% endblock %}
</div>
继承共有部分,然后重写差异化部分:
%{% extends 'layout.html' %}{% block content%}<h1>首页</h1>
{% endblock %}
3.用户管理
7.1新建用户
- 原始方法实现思路(较本质,但麻烦):
- 用户提交的数据,校验比较麻烦
- 如果出现字段不合法,应该有字段不合法提示
- 页面渲染,每一个字段都需要重写一遍
- 对于关联表,还要自己去表查询后渲染
- Django组件实现:
- Form组件(中等简便):只能解决前三点,最后一个关联表查询还需要自己写
- ModelForm组价(最简便):针对数据库中的某个表建议使用ModelForm
7.2Dangjo的Form组件
views.py中:
class Myform(Form): #Dajango中的Formuser = forms.CharField(widget = forms.Input)pwd = forms.CharField(widget = forms.Input)emaill = forms.EmailField(widget = forms.Input)def user_add(request):"""添加用户(原始方式)"""if request.method == "GET":form = Myform()return render(request, 'user_add.html', {'form':form})
在user_add.html中
<form class="form-horizontal" method="post">{{form.user}}{{form.pwd}}{{form.email}}<!-->自动生成HTML标签,代替下面的:<input type="text" class="form-control" name="name" placeholder="请输入部门名称"><!--></form>
还能更简洁的方式:
<form class="form-horizontal" method="post">{% for field in form%}{# 会循环将form中的字段转换成HTMl渲染在页面上 #}{{field}}{% endfor %}
</form>
7.3 Dangjo的ModelForm组件()
1.model.py中
class UserInfo(models.Model):"""员工表"""name = models.CharField(verbose_name="姓名", max_length=16)password = models.CharField(verbose_name="密码", max_length=64)age = models.IntegerField(verbose_name='年龄')account = models.DecimalField(verbose_name='账户余额', max_digits=10, decimal_places=2, default=0)creat_time = models.DateTimeField(verbose_name='入职时间')depart = models.ForeignKey(to='Department', to_field='id', on_delete=models.CASCADE)depart = models.ForeignKey(to='Department', to_field='id', blank=True, null=True, on_delete=models.SET_NULL)gender_choices = ((0, '女'),(1, '男'))gender = models.SmallIntegerField(verbose_name='性别,男1,女0', choices=gender_choices)
2.views.py中
class Myform(ModelForm):#支持自定义字段 xx = form.CharField('...')class Meta:model = UserInfofields = ['name','password','age','creat_time','depart','gender','xx']def user_add(request):"""添加用户(原始方式)"""if request.method == "GET":form = Myform()return render(request, 'user_add.html', {'form':form})
3.user_add.html中
<form class="form-horizontal" method="post">{% for field in form%}{# 会循环将form中的字段转换成HTMl渲染在页面上 #}{{field}}{% endfor %}
</form>
7.4 编辑用户
from django import formsclass UserModelForm(forms.ModelForm):name = forms.CharField(min_length=3, max_length=16, label='姓名')# password = forms.CharField(label='密码', validators=re.compile(r'\d+'))class Meta:model = models.UserInfofields = ['name', 'password', 'age', 'account', 'creat_time', 'gender', 'depart']# 这种方式太麻烦了# widgets = {# 'name': forms.TextInput(attrs={'class': 'form-control'}),# 'age': forms.PasswordInput(attrs={'class': 'form-control'}),# 'account': forms.TextInput(attrs={'class': 'form-control'}),# 'creat_time': forms.TextInput(attrs={'class': 'form-control'}),# 'gender': forms.TextInput(attrs={'class': 'form-control'}),# 'depart': forms.TextInput(attrs={'class': 'form-control'}),# }# 简写:重写初始化方法,找到对应的插件,为其加上属性def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)# 循环找到所有插件, 为其加入class= 'form-control'for name, field in self.fields.items():print(name, field)field.widget.attrs = {'class': 'form-control', 'placeholder': f"请输入{field.label}"}def user_add_bymodelform(request):"""添加用户 by ModelForm"""if request.method == "GET":form = UserModelForm()return render(request, 'user_add_bymodelform.html', {'form': form})# POST提交数据,数据校验,存入数据库form = UserModelForm(data=request.POST)if form.is_valid():print(form.cleaned_data)# 如果数据合法,保存到数据库form.save()# 校验失败,返回错误信息print(form.errors)return render(request, 'user_add_bymodelform.html', {'form': form})def user_edit(request, id):"""编辑用户"""row_object = models.UserInfo.objects.filter(id=id).first()if request.method == "GET":# 根据id获取要更新的记录form = UserModelForm(instance=row_object)return render(request, 'user_edit.html', {'form': form})# POSTform = UserModelForm(data=request.POST, instance=row_object)if form.is_valid():# data=request.POST默认保存的是用用户输入的值,如果还需要加入一些字段值,可以# form.instance.字段名 = 新值form.save()return redirect('/user/list')return render(request, 'user_edit.html', {'form': form})def user_delete(request, id):models.UserInfo.objects.filter(id=id).delete()return redirect('/user/list')
7.5 模糊搜索
# 之前的搜索
models.PrettyNumber.objects.filter(id=XX,number=XXX)dict_data = {'id'XX, "number":XXX}
models.PrettyNumber.objects.filter(**dict_data)
Django中的对于数字的模糊搜索:
models.PrettyNumber.objects.filter(id=XX) # id=12
models.PrettyNumber.objects.filter(id__gt=XX) # id大于12
models.PrettyNumber.objects.filter(id__gte=XX) # id大于等于12
models.PrettyNumber.objects.filter(id__lt=XX) # id小于12
models.PrettyNumber.objects.filter(id__lte=XX) # id小于等于12
Django中的对于字符串的模糊搜索:
models.PrettyNumber.objects.filter(number="139") #字符串number筛选出完全等于139
models.PrettyNumber.objects.filter(number__startswith="139") #字符串number筛选出以139开头
models.PrettyNumber.objects.filter(number__endswith="155") #字符串number筛选出以155结尾
models.PrettyNumber.objects.filter(number__contains="999") #字符串number筛选出包含999
models.PrettyNumber.objects.filter(number__startswith="139") #字符串number筛选出以139开头
# 当然,也可以使用字典形式
data_dict = {"number__contains":"999"}
models.PrettyNumber.objects.filter(**data_dict) #字符串number筛选出包含999
7.6 分页
models.PrettyNumber.objects.all()[:10] # 取到前10
models.PrettyNumber.objects.filter(number__contains ="999")[5:10]# 数据库的总条数
counts = models.PrettyNumber.objects.all().count()
# 获取price=XXX 的数据条数
counts = models.PrettyNumber.objects.filter(price=XXX).count()
使用字典形式
data_dict = {“number__contains”:“999”}
models.PrettyNumber.objects.filter(**data_dict) #字符串number筛选出包含999
7.6 分页
models.PrettyNumber.objects.all()[:10] # 取到前10
models.PrettyNumber.objects.filter(number__contains ="999")[5:10]# 数据库的总条数
counts = models.PrettyNumber.objects.all().count()
# 获取price=XXX 的数据条数
counts = models.PrettyNumber.objects.filter(price=XXX).count()