关于加密:如何将用户模型传递到表单字段(django)?

How can I pass a User model into a form field (django)?

基本上,我需要使用用户的密码散列来通过自定义模型字段加密一些数据。看看我在这里使用的代码片段:django加密。

我试过这个:

1
2
3
4
5
6
7
8
9
10
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))

但是当我尝试使用用户字段时,我会得到一个foreignkey实例(当然!):

1
2
user_field = kwargs.get('user_field')
cipher = user_field.password[:32]

感谢您的帮助!


可能是这样的-重写save()方法,您可以在其中调用encrypt方法。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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

也许有一种更优雅的"Python"方式