简体   繁体   English

使用CreateView / ModelForm和自定义清理方法时在django中验证模型

[英]Model validating in django when using CreateView/ModelForm with custom clean method

I'm trying to set a simple form, for user to input IP subnet into my django app. 我正在尝试设置一个简单的表单,供用户将IP子网输入到我的django应用程序中。 I want to validate that IP + Mask is a subnet address. 我想验证IP + Mask是一个子网地址。 I'm using CreateView with IpRangeForm. 我正在使用CreateView和IpRangeForm。 However, I've noticed a problem, that when I override ModelForm clean method, my model validation doesn't work. 但是,我注意到一个问题,当我覆盖ModelForm的clean方法时,我的模型验证不起作用。

Model: 模型:

class IpSubnet(models.Model):
    ip = models.GenericIPAddressField(verbose_name="IP", protocol='IPv4')    
    mask = models.IntegerField(verbose_name="Mask", default=24, validators=[MaxValueValidator(32), MinValueValidator(0)]))

View: 视图:

class IpSubnetCreateView(SuccessMessageMixin, CreateView):
    form_class = IpSubnetForm 
    model = IpSubnet   
    success_url = '/front/'
    success_message = "%(ip)s/%(mask)s added"

ModelForm: 的ModelForm:

class IpSubnetForm(forms.ModelForm):
    class Meta:
        model= IpSubnet
        fields = ( 'ip','mask')

    def clean(self):
        cleaned_data = super(IpSubnetForm, self).clean()
        ip = cleaned_data.get('ip')
        mask = cleaned_data.get('mask')

        subnet = ipcalc.Network(ip + "/" + str(mask))
        if ip != subnet.network():
            raise ValidationError(
                _('%(ip)s/%(mask)s is not a network address (network address: %(network)s/%(mask)s)'),
                params={'ip':str(ip), 'mask' : str(mask), 'network':str(subnet.network())},
            )
        return cleaned_data

If I delete my clean method, model validation works fine. 如果我删除我的干净方法,模型验证工作正常。 With my clean method, only the subnet validation works, so user can input ie chars into IP field. 使用我的clean方法,只有子网验证可以工作,因此用户可以输入ie chars到IP字段。 I don't see any difference if I add or delete call to parent: 如果我添加或删除对父母的调用,我没有看到任何区别:

super(IpSubnetForm, self).clean()

Therefore it looks like in my case I should use some other way? 因此,在我的情况下,我应该使用其他方式?

How can I fix it, what mistake am I making? 我怎么能解决它,我犯了什么错误?

So after more investigetion into how validation in django works, and thanks to this answer, this is the solution: 因此,在对django中的验证如何工作进行更多的研究之后,由于这个答案,这就是解决方案:

def clean(self):      
    cleaned_data = super(IpRangeForm, self).clean()

    if any(self.errors):
        return self.errors

The problem was that validation did run, but it didn't stop from running the cleanning method. 问题是验证确实运行了,但它并没有停止运行清理方法。 Therefore it raises an exception, about me trying to work with NoneType. 因此,它引发了一个例外,关于我尝试使用NoneType。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Django:使用Model-Mommy测试自定义ModelForm的“清理”方法 - Django: Testing the 'clean' method of a custom ModelForm using Model-Mommy 保持django模型清理方法验证外键对象并使用ModelForm保存 - keeping django models clean method validating foreign key object and using ModelForm save 在ModelForm清理之前,模型验证器未验证 - Model validator not validating before ModelForm clean 在为 Django 模型创建表单时使用 CreateView 和 forms.Modelform 之间的区别? - Difference between using CreateView and forms.Modelform in creating a form for a django model? django 中的单个 CreateView 用于将多个 ModelForm 数据提交到多个 Model - Single CreateView in django for submitting multiple ModelForm data to multiple Model Django ModelForm无法使用自定义日期格式正确验证 - Django ModelForm not validating correctly with custom date format 使用自定义clean_时键入Error <fieldname> django中的方法 - Type Error when using custom clean_<fieldname> method in django 在我的Django ModelForm中覆盖Clean方法 - Overriding the Clean method in my Django ModelForm 验证表单时未调用 django 清洁方法 - django clean method is not being called when validating form 使用createview和modelform在django中自动将登录用户设置为作者 - Automatically set logged-in user as the author in django using createview and modelform
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM