Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom field's to_python not working? - Django

I'm trying to implement an encrypted char field.


I'm using pydes for encryption

This is what I have:

from pyDes import triple_des, PAD_PKCS5
from binascii import unhexlify as unhex
from binascii import hexlify as dohex

class BaseEncryptedField(models.CharField):

    def __init__(self, *args, **kwargs):
        self.td = triple_des(unhex('c35414909168354f77fe89816c6b625bde4fc9ee51529f2f'))
        super(BaseEncryptedField, self).__init__(*args, **kwargs)

    def to_python(self, value):
        return self.td.decrypt(unhex(value), padmode=PAD_PKCS5)

    def get_db_prep_value(self, value):
        return dohex(self.td.encrypt(value, padmode=PAD_PKCS5))

The field is saved encrypted in the database succesfully

but when retireved it does not print out the decrypted version


Any ideas?

like image 670
RadiantHex Avatar asked Oct 21 '10 13:10

RadiantHex


1 Answers

You've forgotten to set the metaclass:

class BaseEncryptedField(models.CharField):

    __metaclass__ = models.SubfieldBase

    ... etc ...

As the documentation explains, to_python is only called when the SubfieldBase metaclass is used.

like image 132
Daniel Roseman Avatar answered Oct 19 '22 14:10

Daniel Roseman