如何将用户模型传递到表单域(django)? [英] How can I pass a User model into a form field (django)?
问题描述
基本上,我需要使用用户密码哈希来通过自定义模型字段加密一些数据。查看我在这里使用的代码段: Django加密。
Basically, I need to use the User's password hash to encrypt some data via a custom model field. Check out the snippet I used here: Django Encryption.
我尝试过:
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实例(当然!):
But when I try to use user_field, I get a ForeignKey instance (of course!):
user_field = kwargs.get('user_field')
cipher = user_field.password[:32]
任何帮助不胜感激!
推荐答案
可能是这样的 - 覆盖save()方法,您可以在其中调用encrypt方法。
maybe something like this - override the save() method where you can call encrypt method.
对于解密,您可以使用 signal post_init ,所以每次从数据库中实例化模型时,product_id字段将自动解密
for decrypt you can use signal post_init, so every time you instantiate the model from the database the product_id field is decrypted automatically
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这样做的方式
maybe there is a more elegant "pythonic" way of doing this
这篇关于如何将用户模型传递到表单域(django)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!