【django学习-21】ModelForm方式,自定义数据校验

  • 前言:我们在使用ModelForm新增数据时,除了使用默认的数据校验之外,还可以自定义数据校验
  • 例如:有个靓号的列表,新增/编辑校验
  • 1.代码示例
    • 1.1:modles.py
class PrettyNum(models.Model):
    """靓号表"""
    mobile = models.CharField(verbose_name="手机号",max_length=11)
    price = models.IntegerField(verbose_name="价格",default=0,null=True,blank=True)

    level_choices = (
        (1,"1级"),
        (2,"2级"),
        (3,"3级"),
        (4,"4级"),
    )
    level = models.SmallIntegerField(verbose_name="级别",choices=level_choices,default=1)

    status_choices = (
        (1,"已占用"),
        (2,"未使用"),
    )
    status = models.SmallIntegerField(verbose_name="状态",choices=status_choices,default=2)
  • 1.2:form.py
from app01.utils.bootstrap import BootStrapModelForm
from app01 import models
from django import forms
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
class PrettyModelForm(BootStrapModelForm):
    # 校验字段,方式1
    mobile = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r'^1\d{10}$',"手机号格式错误"),],
    )

    class Meta:
        model = models.PrettyNum
        # fields = "__all__"   # 所有字段
        # exclude = ["mobile"]   # 排除某些字段
        fields = ["mobile","price","level","status"]

    # def __init__(self, *args, **kwargs):
    #     super().__init__(*args, **kwargs)
    #     for name, field in self.fields.items():
    #         field.widget.attrs = {"class": "form-control","placeholder":field.label}

    # # 校验字段,方式2,钩子函数
    def clean_mobile(self):
        txt_mobile = self.cleaned_data["mobile"]
        flag = models.PrettyNum.objects.filter(mobile=txt_mobile).exists()  # 判断是否存在,返回True、False
        if flag:
            raise ValidationError("手机号已存在")

        if len(txt_mobile) != 11:
            # 验证不通过
            raise ValidationError("格式错误")
        # 验证通过,用户输入的值返回
        return txt_mobile
  • 1.3:views.py
from django.shortcuts import render, redirect
from app01 import models
from app01.utils.pagination import Pagination
from app01.utils.form import UserModelForm, PrettyModelForm, PrettyEditModelForm

def pretty_add(request):
    """ 添加靓号 """
    if request.method == "GET":
        form = PrettyModelForm()
        return render(request, 'pretty_add.html', {"form": form})
    form = PrettyModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/pretty/list/')
    return render(request, 'pretty_add.html', {"form": form})


def pretty_edit(request, nid):
    """ 编辑靓号 """
    row_object = models.PrettyNum.objects.filter(id=nid).first()

    if request.method == "GET":
        form = PrettyEditModelForm(instance=row_object)
        return render(request, 'pretty_edit.html', {"form": form})

    form = PrettyEditModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/pretty/list/')

    return render(request, 'pretty_edit.html', {"form": form})
  • 1.4:实现效果
posted @ 2024-05-13 22:33  Tony_xiao  阅读(38)  评论(0编辑  收藏  举报