如何将用户模型传递到表单字段(django)?
基本上,我需要使用用户的密码哈希通过自定义模型字段来加密一些数据。查看我在这里使用的代码片段: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 时,我得到一个外键实例(当然!):
user_field = kwargs.get('user_field') cipher = user_field.password[:32]
感谢任何帮助!
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.
I tried this:
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))
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]
Any help is appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许是这样的 - 重写 save() 方法,您可以在其中调用加密方法。
为了解密,您可以使用 signal post_init ,因此每次实例化模型时从数据库中,product_id 字段会自动解密,
也许有一种更优雅的“pythonic”方式可以做到这一点
maybe something like this - override the save() method where you can call encrypt method.
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
maybe there is a more elegant "pythonic" way of doing this