どのように私は、フォームフィールド(ジャンゴ)にUserモデルを渡すことができますか?

StackOverflow https://stackoverflow.com/questions/1743764

質問

基本的に、私はカスタムモデルフィールドを経由していくつかのデータを暗号化するために、ユーザーのパスワードハッシュを使用する必要があります。私はここで使用するスニペットをチェックアウト:。 Djangoの暗号化する

私はこれを試してみました。

class MyClass(models.Model):
    owner = models.ForeignKey(User)
    product_id = EncryptedCharField(max_length=255, user_field=owner)

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

    def formfield(self, **kwargs):
        defaults = {'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')
cipher = user_field.password[:32]

すべてのヘルプは歓迎です!

役に立ちましたか?

解決

このような多分何か - あなたは暗号化メソッドを呼び出すことができ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

多分これを行うにはよりエレガントな「神託」方法がある。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top