开发者

Custom field's to_python not working? - Django

开发者 https://www.devze.com 2023-01-20 23:55 出处:网络
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

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), pa开发者_如何学运维dmode=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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消