1、获取数据
row_object = models.UserInfo.objects.filter(id=nid).first()
if request.method == "GET":
form = UserModelForm(instance=row_object)
return render(request,'user_edit.html',{"form":form})
2、更新数据
ModelForm 实例参数:instance=row_object
form=UserModelForm(data=request.POST,instance=row_object)
if form.is_valid():
form.save()
return redirect("/user/list/")
return render(request,'user_edit.html',{"form":form})
3、数据排序 order_by
ASC(正序):models.PrettyNum.objects.all().order_by(“level”)
DESC(倒序):models.PrettyNum.objects.all().order_by(“-level”)
4、排除字段 exclude
# 全副字段
fields = "__all__"
#排除某一字段
exclude = ['level']
5、对用户提交的数据进行格局的校验
5.1 正则表达式
from django.core.validators import RegexValidator
class PrettyModelForm(forms.ModelForm):
'''新建靓号'''
mobile = forms.CharField(
label="手机号",
validators=[RegexValidator(r'^1[3-9]\d{9}$','手机号格局谬误')]
)
class Meta:
model = models.PrettyNum
# fields = ['mobile','price','level','status']
fields = "__all__"
5.2 勾子办法
clean_字段名
#验证办法 -2: 勾子办法
from django.core.exceptions import ValidationError
def clean_mobile(self):
txt_mobile = self.cleaned_data['mobile']
if len(txt_mobile) != 11:
#验证不通过
raise ValidationError("格局谬误")
#验证通过,返回用户输出的值
return txt_mobile
6、重定义 ModelForm
class PrettyEditModelForm(forms.ModelForm):
'''编辑靓号,定义须要编辑的字段'''
mobile = forms.CharField(disabled=True,label="手机号")
class Meta:
model = models.PrettyNum
fields = ['mobile','price','level','status']
def pretty_edit(request,nid):
'''编辑靓号'''
row_object = models.PrettyNum.objects.filter(id=nid).first()
if request.method == "GET":
form = PrettyEditModelForm(instance=row_object) #如果只容许批改局部字段,须要为编辑性能独自写 ModelForm
6、查问判断反复字段
6.1 查问判断反复字段
exists = models.PrettyNum.objects.filter(mobile=XXXX).exists()
if exists:
raise ValidationError("查问的字段已存在")
6.2 排除本身外的其余反复字段
self.instance.pk
exists = models.PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=XXXX).exists()