How to use hex numbers in Django

django, python-3.5

Solution

So if you want the user to submit a number like `0x04`, you'll need to send those as strings. On the back end, parse them as a base-16 integer:

# input_string = "0x04"
n = int(input_string, 16)
=> n = 4

Store them on the model, base doesn't matter here:

your_model.number = n

When displaying, simply use `hex()`:

print hex(your_model.number)
=> 0x4

print hex(15)
=> "0xf"

Or better use the "%x" formatter:

>>> print "%x" % 100
64
>>> print "0x%x" % 100
64

Which will allow you to pad the number with zeroes...

>>> print "%06x" % 100
000064

Problem

I'm new to Django (and python) and I'm trying to use hexadecimal numbers. I have a model in which I use a PositiveIntegerField. But I'd like to enter numbers like 0x0000 in the form, and display as hex too when I list the table. Where should I look to have this behavior ? A custom widget, a manager, a meta subclass ? I have so much to learn (oh yeah baby!) but so little time. A little help to know where to look for would be appreciated :) Thanks

Original source