gpt4 book ai didi

django - 如何在保存到数据库之前加密 TextField

转载 作者:行者123 更新时间:2023-12-02 00:53:29 28 4
gpt4 key购买 nike

我在这里尝试创建可以保存密码的模型,这里是我的模型:

class Server(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=20, null=True)
hostname = models.CharField(max_length=50, null=True, blank=True)
ip = models.GenericIPAddressField()
ip2 = models.GenericIPAddressField(null=True, blank=True)
user_name = models.CharField(max_length=20, null=True)
password = models.TextField(max_length=500, null=True, blank=True)
ssh_key = models.FileField(null=True, blank=True, upload_to='Keys/')

直到现在我读了很多博客和帖子,但我还没有找到任何好的方法来将加密文本保存到数据库中

我正在尝试这种方法,但它对我也不起作用,请检查下面的 View.py,

from cryptography.fernet import Fernet
class HostCreate(CreateView):
model = Server
template_name = 'inventory/host_create.html'
form_class = HostForm

# after getting POST data of fields (name, hostname, ip, pass, key) adding user and saving
def form_valid(self, form):
host = form.save(commit=False)
host.user = User.objects.get(pk=self.request.user.pk)
host.password = self.ecrypt(host.password)
host.save()
return redirect('inventory:hosts')

def ecrypt(self, password): # need password and return cipher password
key = 'wgjSSyfVKgz0EjyTilqeJSaANLDu7TzHKdpAXUeZPbM='
cipher_suite = Fernet(key)
cipher_text = cipher_suite.encrypt(password)
return cipher_text

这里出现错误,

Exception Type:     TypeError
Exception Value: data must be bytes.
Exception Location: /usr/lib64/python2.7/site-packages/cryptography/fernet.py in _encrypt_from_parts, line 55

密码字段是否有内置的 django 功能?

最佳答案

您可以通过两种可能的方式做到这一点。

  1. 像这样为您的模型编写自定义保存方法

    class Server(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=20, null=True)
    hostname = models.CharField(max_length=50, null=True, blank=True)
    ip = models.GenericIPAddressField()
    ip2 = models.GenericIPAddressField(null=True, blank=True)
    user_name = models.CharField(max_length=20, null=True)
    password = models.TextField(max_length=500, null=True, blank=True)
    ssh_key = models.FileField(null=True, blank=True, upload_to='Keys/')

    def save(self, *args, **kwargs):
    if not self.pk:
    # encrypt_field_value_here
    super(Server, self).save(*args, **kwargs)
  2. 您可以使用自定义模型字段。您可以从 here 获得相关文档.还要检查 here 中的 BaseEncryptedField .

您还可以使用 this包。

关于django - 如何在保存到数据库之前加密 TextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37741339/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com