0
votes

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
What's SomeModel like? What is the type of SomeModel.number? os.urandom() doesn't return numbers, it returns bytes (also str in python2). - Ilja Everilä
I have made number field in model as a CharField, so maybe there is the problem. Yep, I know that it returns bytes, but how I can encode it, so Sqlite can store it? I'll update the model to the question. - MMakela
This seems relevant: docs.djangoproject.com/en/1.9/ref/models/fields/#binaryfield "A field to store raw binary data. It only supports bytes assignment. Be aware that this field has limited functionality. For example, it is not possible to filter a queryset on a BinaryField value." - Ilja Everilä

1 Answers

1
votes

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