Store os.urandom variable to Sqlite database in Django

我是研究僧i 提交于 2019-12-13 06:11:56

问题


I'm trying to store random variable to Sqlite database in Django, but I get this error:

You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings.

Here is my code:

random_number = os.urandom(16)
SomeModel.objects.filter(id=2).update(number=random_number)

Models.py:

class SomeModel(models.Model):
    random = models.CharField(max_length=32)

I use Python 2.7.10 and Django 1.9.


回答1:


If still possible, you could alter your model to use BinaryField:

class SomeModel(models.Model):
    random = models.BinaryField(max_length=32)

If on the other hand the model is already set in stone, consider some binary to text encoding, like base64:

from base64 import b64encode

random_number = os.urandom(16)
SomeModel.objects.filter(id=2).update(number=b64encode(random_number))


来源:https://stackoverflow.com/questions/37178657/store-os-urandom-variable-to-sqlite-database-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!