ModelForm错误验证自定义钩子和全局钩子

当需要对model_class中字段作进一步验证,作进一步的约束时,需要使用到钩子,即claan_xxx和clean方法.其返回的errors有点不是那么好处理.看示例.
 
1.Model_class:
class Permission(models.Model):
    """
    权限
    """
    caption = models.CharField(verbose_name='权限名称', max_length=32)
    url = models.CharField(max_length=128)
    menu = models.ForeignKey(Menu, verbose_name='所属菜单', related_name='permissions', null=True, blank=True)
 
    def __str__(self):
        return "%s" % (self.caption,)
View Code
2.Model_Form:
from django.core.exceptions import ValidationError
class PermissionModelForm(ModelForm):
    url= fields.ChoiceField()
 
    class Meta:
        model=models.Permission
        fields="__all__"
 
    def __init__(self,*args,**kwargs):
        super(PermissionModelForm,self).__init__(*args,**kwargs)
        from pro_crm.urls import urlpatterns
        self.fields['url'].choices=get_all_url(urlpatterns,"/",True)
 
    def clean_caption(self):
        raise ValidationError("name有问题")
 
    #全局钩子
    def clean(self):
        print(self.cleaned_data)
        raise ValidationError("密码不一致")
 
3.最终效果如下:
4.其错误是如何取出来展示的呢:
1.ModelForm在清理数据时,单个字段的错误,可以通过xxx.errors.0取出来,这里的xxx指的是for item in form中的xxx,是一个字段对象:
obj = ModelForm()
for item in obj:
    item.label,item.error.0 item
 
或者在html页面:{{ item.errors.0 }}
2.全局的错误,也就是def clean中的错误,藏在form_obj['__all__']中,无法在前端通过模板语言获取,只能在后端取出后送到前端渲染
     @register.inclusion_tag('arya/change_form.html')
def show_form(form):
 
    error_all=form.errors.get('__all__')#全局错误信息
 
    return {'form': form,"error_all":error_all}
 
前端显示:{{ error_all.0 }}    
 
 
 
 
原文地址:https://www.cnblogs.com/jec1999/p/7736871.html