简体   繁体   中英

Store os.urandom variable to Sqlite database in Django

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.

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM