[Ncr-Python.in] why does to_python gets called twice in this code ?

Gora Mohanty gora at mimirtech.com
Tue Jan 8 18:06:21 CET 2013


On 8 January 2013 18:02, Vijay Shanker <deontics at gmail.com> wrote:
> hi
> I am struck trying to write a simple custom django field that inherits
> ForeignKey ..i posted the same at stackoverflow..
>
> http://stackoverflow.com/questions/14214530/why-is-to-python-called-twice-in-this-custom-field-when-saving-an-object-insta
> any help or pointers are welcome.

It is hard to definitively tell why to_python() is called twice,
without digging through the Django admin. code. My guess is
that:
* As you have set SubfieldBase metaclass, it is called once when
  the field is created.
* It is called again on form validation: "The to_python() method
  on a Field is the first step in every validation."
  https://docs.djangoproject.com/en/dev/ref/forms/validation/

However, the problem probably lies in your code, which seems
a bit confused for the ProfiledUserField class:
* to_python() should be prepared to accept values of None, if
  null=True is allowed. Please see the note at the bottom of
  the section https://docs.djangoproject.com/en/dev/howto/custom-model-fields/#converting-database-values-to-python-objects
* Your to_python() function seems to serve no purpose. For
   a ForeignKey field that you derive from, the returned value
   should be an integer, and not an instance of User as you
   seem to be assuming.. Thus, the to_python() function, as
   in the base class (deriving from django.db.models.Field),
   could simply be:
   def to_python(self, value):
       return value
   I.e., there is no need to override this function that I can see.
* Your __init__() function serves no purpose either: max_length
   is not a valid keyword argument for
   django.db.models.fields.related.ForeignKey

I stopped reading at this point as it is increasingly seeming
like a XY problem: http://people.apache.org/~hossman/#xyproblem
People might better be able to help you if you would explain
what you are trying to achieve.

Regards,
Gora


More information about the Ncr-Python.in mailing list