• Django中Model-Form验证


    Django中Model-Form验证

    class UserType(models.Model):
        caption=models.CharField(max_length=32)
    
    
    class UserInfo(models.Model):
        username=models.CharField(max_length=32,verbose_name='用户名')
        email = models.EmailField(verbose_name='邮箱')
    
        user_type = models.ForeignKey(to='UserType',to_field='id',on_delete='on_delete')
    models.py
    class Modelform(forms.ModelForm):   # modelForm
    
        class Meta:                            #Meta类
            model = models.UserInfo
            fields = '__all__'    #__all__列出所有的字段
            # fields = ['username','email']
            # exclude = ['user_type']  #排除
    
    
    def model_form(request):
    
        if request.method == "GET":
            obj = Modelform()
            return render(request,'modelform.html',{'obj':obj})
        elif request.method == "POST":
            obj = Modelform(request.POST)
            print(obj.is_valid())
            print(obj.cleaned_data)
            return render(request, 'modelform.html', {'obj': obj})
    views.py
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    
    <form action="/xiaoqing/model_form/"  method="post">
    {% csrf_token %}
        {{ obj.as_p }}
    <input type="submit" value="提交">
    </form>
    
    </body>
    </html>
    modelform.html
    from django.forms import widgets as Fwidgets
    class Modelform(forms.ModelForm):   # modelForm
    
        class Meta:
            model = models.UserInfo
            fields = '__all__'    #__all__列出所有的字段
            # fields = ['username','email']
            # exclude = ['user_type']  #排除
            labels = {'username':'用户名','email':'邮箱',}
            # 也可以这样设置  不在models.py里设置
            widgets = {
                'username': Fwidgets.Textarea(attrs={'class': 'c1'})
    
            }
            help_texts = {'username': '提示信息'}
    
            error_messages = {
    
                'email':{'required':'邮箱不能为空',}
            }

     Model-Form组件

    ModelForm
        a.  class Meta:
                model,                           # 对应Model的
                fields=None,                     # 字段
                exclude=None,                    # 排除字段
                labels=None,                     # 提示信息
                help_texts=None,                 # 帮助提示信息
                widgets=None,                    # 自定义插件
                error_messages=None,             # 自定义错误信息(整体错误信息from django.core.exceptions import NON_FIELD_ERRORS)
                field_classes=None               # 自定义字段类 (也可以自定义字段)
                localized_fields=('birth_date',) # 本地化,如:根据不同时区显示数据
                如:
                    数据库中
                        2016-12-27 04:10:57
                    setting中的配置
                        TIME_ZONE = 'Asia/Shanghai'
                        USE_TZ = True
                    则显示:
                        2016-12-27 12:10:57
        b. 验证执行过程
            is_valid -> full_clean -> 钩子 -> 整体错误
     
        c. 字典字段验证
            def clean_字段名(self):
                # 可以抛出异常
                # from django.core.exceptions import ValidationError
                return "新值"
        d. 用于验证
            model_form_obj = XXOOModelForm()
            model_form_obj.is_valid()
            model_form_obj.errors.as_json()
            model_form_obj.clean()
            model_form_obj.cleaned_data
        e. 用于创建
            model_form_obj = XXOOModelForm(request.POST)
            #### 页面显示,并提交 #####
            # 默认保存多对多
                obj = form.save(commit=True)
            # 不做任何操作,内部定义 save_m2m(用于保存多对多)
                obj = form.save(commit=False)
                obj.save()      # 保存单表信息
                obj.save_m2m()  # 保存关联多对多信息
     
        f. 用于更新和初始化
            obj = model.tb.objects.get(id=1)
            model_form_obj = XXOOModelForm(request.POST,instance=obj)
            ...
     
            PS: 单纯初始化
                model_form_obj = XXOOModelForm(initial={...})
  • 相关阅读:
    Centos 7环境下配置MySQL 5.7读写分离
    Centos 7环境下安装配置MySQL 5.7
    Hadoop 2.8集群安装及配置记录
    ASP.NET Core 1.1版本之Hello word
    Hadoop版Helloworld之wordcount运行示例
    SSH配置免密登陆设置汇总
    最小安装模式下Centos7.*网卡启动配置
    骚扰式管理
    项目团队之分工协作
    利用微软AntiXss Library过滤输出字符,防止XSS攻击
  • 原文地址:https://www.cnblogs.com/sunhao96/p/9020201.html
Copyright © 2020-2023  润新知