Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opposite of to_python in custom Django form field?

Tags:

python

django

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?

like image 354
Gill Bates Avatar asked Jun 20 '15 13:06

Gill Bates


1 Answers

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>'
like image 59
sthzg Avatar answered Nov 03 '22 01:11

sthzg