问题
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