Django学习笔记010-ModelForm相关

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()

你可能感兴趣的:(django)