首页 文章

Django奇怪的SlugField验证,在clean()之前没有引发错误,返回了未清理的数据

提问于
浏览
3
django 2.0

我有一个django模型,有不同的slug字段:

from django.core.validators import validate_slug

class MyModel(models.Model):
     # with slug field
     slug_field = models.SlugField(max_length=200)

     # or charfield with slug validator (should be exactly the same)
     char_field = models.CharField(max_length=200, validators=[validate_slug])

我的第一个问题,在我的形式,我有一个干净的方法,来验证多个字段的值,而不是单独的 . 理论上应该在 clean_fields 方法之后调用此方法,但即使 clean_fields 引发错误也会调用它 .

我的forms.py:

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = '__all__'

    def clean(self):
        cleaned_data = super().clean()
        print(cleaned_data.get('slug_field'))  # > None
        print(cleaned_data.get('char_field'))  # > ééé; uncleaned data
        print(self.errors)  # only from slug_field
        return cleaned_data

使用SlugField时, slug_field 未在 cleaned_data 中设置,当它's invalid, and after the error is raised and returned to the user by the form. (I don' t看到为什么甚至达到 clean() 时,因为 clean_fields() 之前已经引发了错误)

问题是 CharField 与任何自定义验证器( validate_slug 或自制验证器), cleaned_data 中返回未清除的值 . 但是,仍然会提出验证错误,但之后 .

这对我来说非常 dangerous ,因为我曾经信任 cleaned_data ,修改未保存在模型中的数据 .

1 回答

  • 5

    在字段's validator. If the alias is invalid, then it won' t在 cleaned_data 之后调用 clean() 方法 . 你的 clean 方法应该处理这种情况,例如:

    def clean():
        cleaned_data = super().clean()
        print(self.errors)  # You should see the alias error here
        if 'alias' in cleaned_data:
            print(cleaned_data['alias'])
            # do any code that relies on cleaned_data['alias'] here
        return cleaned_data
    

    有关详细信息,请参阅cleaning fields that depend on each other上的文档 .

相关问题