1

基本的に、カスタムモデルフィールドを介して一部のデータを暗号化するには、ユーザーのパスワードハッシュを使用する必要があります。ここで使用したスニペットを確認してください:DjangoEncryption

私はこれを試しました:

クラスMyClass(models.Model):
    所有者=models.ForeignKey(User)
    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)
        super(EncryptedCharField、self).formfield(** defaults))を返します

しかし、user_fieldを使おうとすると、ForeignKeyインスタンスが取得されます(もちろん!):

user_field = kwargs.get('user_field')
暗号=user_field.password[:32]

どんな助けでも大歓迎です!

4

1 に答える 1

1

おそらくこのようなものです-encryptメソッドを呼び出すことができるsave()メソッドをオーバーライドします。

復号化にはsignalpost_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 に答える