In the docs, there is a passage about to_python
method, responsible for deserializing value. But what is recommended way to serialize data and make it ready for passing to widget? Something like get_db_prep_value()
, but for for fields?
There are the methods value()
and prepare_value()
, the latter of which is undocumented but is called at the end of value()
. If you read the code you can search for prepare_value
and will find that e.g. the date-related fields make use of it to make adjustments to the value if necessary.
value()
is called by as_widget()
which at the end calls the render()
method on the widget and passes the value returned by value()
(and thus prepare_value()
) along.
The latest modifications are made in the widget's render()
method. Only here happens the transformation to the final string representation, which is why in certain use cases (when the widget requires another data type than a string, e.g. select lists which require a list
object) it is necessary to override render()
sepecifically.
However, if the widget deals with strings (or the modifications you wish to make can be applied to the data type that will be passed to render()
) it will be enough to hook into prepare_value()
.
from django import forms
class MyField(forms.Field):
def prepare_value(self, value):
return '{}, I am modified!'.format(value)
class MyForm(forms.Form):
foo = MyField(initial="Hello world")
Testing the snippet in the shell:
In [1]: MyForm().as_p()
Out[1]: '<p><label for="id_foo">Foo:</label> <input id="id_foo" name="foo" type="text" value="Hello world, I am modified!" /></p>'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With