Bug fix for #4

This is a bug fix for issue #4 where Django Admin raises an exception when saving Encrypted fields as the value is not encrypted at the time of the clean process.

This PR sets a semaphore property which is checked within the to_python method allowing the decryption to be skipped. It then removes the semaphore property to clean up the field
This commit is contained in:
Steven Mapes 2021-12-17 17:29:10 +00:00 committed by GitHub
parent 22a5cd4f84
commit 9630b3e5e2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -51,11 +51,21 @@ class EncryptedFieldMixin(object):
return self.to_python(value)
def to_python(self, value):
if value is None or not isinstance(value, str):
if value is None or not isinstance(value, str) or hasattr(self, '_already_decrypted'):
return value
value = self.f.decrypt(bytes(value, 'utf-8')).decode('utf-8')
return super(EncryptedFieldMixin, self).to_python(value)
def clean(self, value, model_instance):
"""
Create and assign a semaphore so that to_python method will not try to decrypt an already decrypted value
during cleaning of a form
"""
self._already_decrypted = True
ret = super().clean(value, model_instance)
del self._already_decrypted
return ret
class EncryptedCharField(EncryptedFieldMixin, models.CharField):
pass