模型验证器在ModelForm清理之前未验证

时间:2014-06-11 18:38:16

标签: python django validation

你有一个模型验证器,它在我的ModelForm clean方法之前没有执行。我的问题是我需要模型验证器先执行并出错,如果没有错误继续使用ModelForm清理方法。

models.py

class CapacityOnDemand(models.Model):
    resource_type = models.IntegerField(choices=RESOURCE_TYPE_CHOICES)
    resource_change_type = models.IntegerField(choices=RESOURCE_CHANGE_TYPE_CHOICES)
    capacity_on_demand_code = models.CharField(max_length=255, help_text=capacity_on_demand_code_help_text, validators=[RegexValidator(capacity_on_demand_code_regex, capacity_on_demand_code_error)])

forms.py

class ResourceCapacityChangeForm(forms.ModelForm):

    class Meta:
        model = CapacityOnDemand

    def clean(self):
        cleaned_data = super(ResourceCapacityChangeForm, self).clean()
        cod_code = cleaned_data.get('capacity_on_demand_code')

        if not is_code_in_sequence(cod_code):
            msg = u"This code is not in sequence. Unable to add code."
            self._errors['capacity_on_demand_code'] = self.error_class([msg])
        return cleaned_data

基于@karthikr回复的工作答案:

models.py

class CapacityOnDemand(models.Model):
    resource_type = models.IntegerField(choices=RESOURCE_TYPE_CHOICES)
    resource_change_type = models.IntegerField(choices=RESOURCE_CHANGE_TYPE_CHOICES)
    capacity_on_demand_code = models.CharField(max_length=255, help_text=capacity_on_demand_code_help_text)

forms.py

class ResourceCapacityChangeForm(forms.ModelForm):

    class Meta:
        model = CapacityOnDemand

    def clean_capacity_on_demand_code(self):
        cod_code = cleaned_data.get('capacity_on_demand_code')

        if not re.match(capacity_on_demand_code_regex, cod_code):
            raise ValidationError(capacity_on_demand_code_error)

        if not is_code_in_sequence(cod_code):
            msg = u"This code is not in sequence. Unable to add code."
            self._errors['capacity_on_demand_code'] = self.error_class([msg])
        return cod_code

1 个答案:

答案 0 :(得分:1)

您可以使用model field's clean,而不是在执行clean之前进行验证。 像这样:

from django.core.exceptions import ValidationError

class ResourceCapacityChangeForm(forms.ModelForm):

    class Meta:
        model = CapacityOnDemand

    def clean_capacity_on_demand_code(self):
        cod_code = self.cleaned_data.get('capacity_on_demand_code')

        if not is_code_in_sequence(cod_code):
            raise ValidationError("This code is not in sequence. Unable to add code.")
        return cod_code