Michael Miller Michael Miller - 17 days ago 13
Python Question

python django id to hex

I'm looking to take the default ID key from the django model turn it into hexadecimal and display it on a page when the user sumbits the post, I've tried several of methods with no success can anyone point me in the right direction?


def post_new(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.published_date = timezone.now()
return redirect('post_detail', pk=post.pk)
form = PostForm()
return render(request, 'books_log/post_edit.html', {'form': form})

Can supply more information if needed.


Python's hex function is all you need here, but the problem is you can't call it directly from your template. So the solution is to add a method to your model.

class MyModel(models.Model):

   def to_hex(self):
       return hex(self.pk)

Then in your template

 {{ my_object.to_hex() }}