Reputation: 3734
The to_python
method of my custom field seems to not get called.
I have:
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',]
I want the form to clear out the (default) value 'http://' if the url is left blank.
But the to_python()
method never gets called. On a POST, it just goes straight to the foo_form.is_valid()
.
I was under the impression that to_python()
happens before the form gets cleaned.
I realize I could do it with javascript, but I'd rather do it this way.
Upvotes: 0
Views: 3260
Reputation: 599778
This is explained in the documentation for custom model fields; you need to add the SubfieldBase
metaclass declaration.
However, this isn't really an appropriate use of a custom field. You should really do this in the form: either via a specific clean_url
method or by providing a custom form field with its own clean
method.
Upvotes: 2