That format is actually text. It’s a text representation of binary data.
Storing it as a text field could be appropriate - it really depends upon what all you’re going to be doing with it.
If you’re only ever going to be displaying them as a
data URL within an img tag, you could directly store these as base64.
Unfortunately, having the ‘\x’ as the first two characters makes this trickier than I think it should be. Python interprets ‘\x89504e470d0a’ as “\x89” “504e470d0a”, where “\x89” is considered 1 character.
For example, from the regular Python shell:
>>> s = '\x89504e470d0a'
Getting rid of that notation and coming up with something usable requires a little bit of trickery.
There are other ways, but what I’ve come up with is:
>>> new_string = format(ord(s), "x") + s[1:]
Once you have the string in a usable format, you can now convert it to bytes and then to a base64 encoding.
>>> binary_data = bytes.fromhex(new_string)
Finally, you can turn it into base64:
>>> import base64
>>> base64_bytes = base64.b64encode(binary_data)
>>> base64_string = base64_bytes.decode()
It’s that last value (base64_string) you’ll want to use in your template for display.
What you choose to store in the dabase is up to you.
- You can store the original string, as text, and do these transformations in the view.
- You can do the conversion to bytes and store it as binary data.
- You can finish the conversion and store the base64 string.