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,当它无效时,以及在引发错误并通过表单返回给用户之后。(我不明白为什么clean()甚至达到,因为clean_fields()之前已经提出了错误)

问题在于,CharField使用任何自定义验证器(validate_slug或自制验证器)时,未清理的值会以cleaned_data. 但是,仍然会引发验证错误,但会在之后。

这对我来说非常危险,因为我曾经相信cleaned_data,修改未保存在模型中的数据。

4

1 回答 1

5

clean()方法在字段的验证器之后调用如果别名无效,那么它将不在cleaned_data. 您的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

有关更多信息,请参阅有关清理相互依赖的字段的文档。

于 2018-02-19T09:57:54.357 回答