【问题标题】:Custom field's to_python not working? - Django自定义字段的 to_python 不起作用? - 姜戈
【发布时间】:2010-10-21 13:53:39
【问题描述】:

我正在尝试实现一个加密的 char 字段。


我正在使用pydes 进行加密

这就是我所拥有的:

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))

字段已成功加密保存在数据库中

但在停用时它不会打印出解密版本


有什么想法吗?

【问题讨论】:

    标签: python django encryption django-models


    【解决方案1】:

    您忘记设置元类:

    class BaseEncryptedField(models.CharField):
    
        __metaclass__ = models.SubfieldBase
    
        ... etc ...
    

    作为the documentation explainsto_python 仅在使用 SubfieldBase 元类时调用。

    【讨论】:

    • 我认为这个答案对于最新版本的 Django 来说已经过时了。
    猜你喜欢
    • 2014-03-11
    • 1970-01-01
    • 1970-01-01
    • 2017-10-15
    • 2017-09-20
    • 1970-01-01
    • 2012-12-14
    • 2020-11-14
    • 2012-12-06
    相关资源
    最近更新 更多