0

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.

MMakela
  • 167
  • 2
  • 16
  • 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ä May 12 '16 at 06:19
  • 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 May 12 '16 at 06:24
  • 1
    This seems relevant: https://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ä May 12 '16 at 06:27

1 Answers1

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))
Ilja Everilä
  • 50,538
  • 7
  • 126
  • 127