models.py
class Department(models.Model):
"""部门表"""
title = models.CharField(max_length=32, verbose_name='部门表')def __str__(self):
return self.titleclass UserInfo(models.Model):
"""员工表"""
name = models.CharField(max_length=16, verbose_name='姓名')
password = models.CharField(max_length=64, verbose_name='密码')
age = models.IntegerField(verbose_name='年龄')
account = models.DecimalField(max_digits=10, verbose_name='账户余额', decimal_places=2, default=0)
create_time = models.DateTimeField(verbose_name='入职时间')
gender_choices = (
(1, '男'),
(2, '女')
)
gender = models.SmallIntegerField(verbose_name='性别', choices=gender_choices)# 级联删除
depart = models.ForeignKey(to='Department', to_field='id', on_delete=models.CASCADE, verbose_name='部门')
【python中使用ModelForm】views.Py
from django import formsclass UserModelForm(forms.ModelForm):
name = forms.CharField(min_length=3, label='用户名')
class Meta:
model = models.UserInfo
fields = ['name', 'password', 'age', 'account', 'create_time', 'gender', 'depart']def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)for name, field in self.fields.items():
#html元素添加属性
field.widget.attrs = {'class': 'form-control'}def user_model_form_add(request):
"""modelForm 添加用户"""
if request.method == 'GET':
form = UserModelForm()
return render(request, 'user_model_form_add.html', {'form': form})# 用户POST提交数据,数据校验
form = UserModelForm(data=https://www.it610.com/article/request.POST)
# 验证数据
if form.is_valid():
# 保存到数据库
form.save()
return redirect('/user/list/')
# print(form.cleaned_data)# 校验失败
print(form.errors)
return render(request, 'user_model_form_add.html', {'form': form})
推荐阅读
- 用了十几年才想明白(Python的精髓居然是方括号、花括号和圆括号!)
- 2022年,你应该知道的Python打包指南
- 如何利用Python找到下一个“游戏驿站”()
- 直观讲解一下 RPC 调用和 HTTP 调用的区别!
- opencv|OpenCV(03图像的算数运算)
- opencv|OpenCV(01图片&视频的加载显示)
- tensorflow|OpenMV(18数字识别)
- alot物联网工程师|四.OpenCv图像的基本变换
- python|(2022.4)Win10最新Anaconda安装Pytorch GPU环境(CUDA)教程(极其适合初学者)