ModelForm上的Django字段to_python()方法

时间:2014-08-13 16:43:20

标签: django django-forms

我的自定义字段的to_python方法似乎没有被调用。

我有:

models.py

class FooURLField(models.URLField):
    def to_python(self, value):
        if value == u'http://':
            return u''
        return value


class Foo(models.Model):
    slug = models.SlugField(unique=True, max_length=128)
    url = FooURLField(blank=True)

forms.py

class FooForm(ModelForm):

    class Meta:
        model = Foo
        exclude = ['slug',]

我希望表单清除(默认)值' http://'如果网址留空。 但to_python()方法永远不会被调用。在POST上,它直接进入foo_form.is_valid()

我认为在表单被清除之前to_python()发生了。 我意识到我可以用javascript做到这一点,但我宁愿这样做。

1 个答案:

答案 0 :(得分:1)

the documentation for custom model fields中对此进行了解释;您需要添加SubfieldBase元类声明。

但是,这并不适合使用自定义字段。您应该在表单中执行此操作:通过特定的clean_url方法或通过提供自己的clean方法的自定义表单字段。