사용자 모델을 양식 필드 (Django)로 전달하려면 어떻게해야합니까?
-
20-09-2019 - |
문제
기본적으로 사용자의 비밀번호 해시를 사용하여 사용자 정의 모델 필드를 통해 일부 데이터를 암호화해야합니다. 여기서 사용한 스 니펫을 확인하십시오. 장고 암호화.
나는 이것을 시도했다 :
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를 사용하려고 할 때 외국 키 인스턴스를 얻습니다 (물론!).
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
어쩌면 더 우아한 "Pythonic"방법 이이 작업을 수행 할 수 있습니다.
제휴하지 않습니다 StackOverflow