2009-11-16 38 views
1

基本上,我需要使用用戶的密碼哈希通過自定義模型字段來加密一些數據。看看我在這裏使用的代碼片段:Django Encryption如何將用戶模型傳遞到表單域(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] 

任何幫助表示讚賞!

回答

1

也許是這樣的 - 重寫save()方法,你可以調用加密方法。

用於解密你可以使用signal 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 

也許有這樣

+0

更優雅「Python化」的方式首先,感謝您的回覆!希望我能想出類似這樣的東西。但是,關於如何用信號完成這個任務,你有沒有一個基本的例子?作爲一個整體,我對信號的知識非常有限...... – Bryan 2009-11-16 18:26:57

+0

增加了信號處理程序,歡呼聲。 – Evgeny 2009-11-16 18:44:34

+0

謝謝!哇,我真的很感動。我一定會在稍後再說。再次感謝! – Bryan 2009-11-16 18:53:11

相關問題