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

标签 python django django-models django-forms django-2.0

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 引发错误也会调用它。

我的表格.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() 之前已经引发了错误)

问题是,对于带有任何自定义验证器(validate_slug 或自制验证器)的 CharField,未清理的值返回到 cleaned_data。但是,仍然会出现验证错误,但是之后。

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

最佳答案

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

请参阅 cleaning fields that depend on each other 上的文档了解更多信息。

关于python - Django 奇怪的 SlugField 验证,在 clean() 之前未引发错误,返回未清理的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48863201/

相关文章:

python - MousePressEvent,QGraphicsView中的位置偏移

python - 如何在 SQLAlchemy 中定义与同一张表的两个关系

python - 如何在 Django forms.py 中获取远程 ip

python - get_object_or_404() 的第一个参数必须是模型、管理器或查询集,而不是 'function'

python - 在 Django 中定义常量

django - 如何将 Django 对象的方法结果存储在我的数据库中?

django - 列出链接到模型的外键

python - Pandas 在 2 列中应用并在一行中替换它们

python - ValueError : Cannot set tensor: Got value of type FLOAT64 but expected type FLOAT32 for input 0, 名称:serving_default_input_1:0

Django 固定主键错误,需要自然键解决方案