1

基本上,我需要使用用户的密码哈希通过自定义模型字段加密一些数据。查看我在这里使用的代码段:Django Encryption

我试过这个:

类 MyClass(models.Model):
    所有者 = 模型。外键(用户)
    product_id = EncryptedCharField(max_length=255, user_field=owner)

..................................................... ...................................

    def formfield(self, **kwargs):
        默认值 = {'max_length': self.max_length, 'user_field': self.user_field}
        defaults.update(kwargs)
        return super(EncryptedCharField, self).formfield(**defaults))

但是当我尝试使用 user_field 时,我得到了一个 ForeignKey 实例(当然!):

user_field = kwargs.get('user_field')
密码 = user_field.password[:32]

任何帮助表示赞赏!

4

1 回答 1

1

可能是这样的 - 覆盖可以调用加密方法的 save() 方法。

对于解密,您可以使用信号 post_init,因此每次从数据库实例化模型时,product_id 字段都会自动解密

class MyClass(models.Model):
    user_field = models.ForeignKey(User)
    product_id = EncryptedCharField()
    ...other fields...

    def save(self):
        self.product_id._encrypt(product_id, self.user_field)
        super(MyClass,self).save()

    def decrypt(self):
        if self.product_id != None:
            user = self.user_field
            self.product_id._decrypt(user=user)

def post_init_handler(sender_class, model_instance):
    if isinstance(model_instance, MyClass):
        model_instance.decrypt()

from django.core.signals import post_init
post_init_connect.connect(post_init_handler)


obj = MyClass(user_field=request.user) 
#post_init will be fired but your decrypt method will have
#nothing to decrypt, so it won't garble your input
#you'll either have to remember not to pass value of crypted fields 
#with the constructor, or enforce it with either pre_init method 
#or carefully overriding __init__() method - 
#which is not recommended officially

#decrypt will do real decryption work when you load object form the database

obj.product_id = 'blah'
obj.save() #field will be encrypted

也许有一种更优雅的“pythonic”方式来做到这一点

于 2009-11-16T18:04:22.263 回答