2009-11-16 75 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