[Django]-How to use hex numbers in Django

4👍

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

Leave a comment