I have a uuid field in my Document model
If I get() my model with a bad uuid, I got a error 500. This line throw an error:
x = Document.objects.get(uuid=object_uuid)
Instead of a 500 I want a 404 error
I wrote this, but I don't want to put my function everywhere it's so redundant (I'm lazy)
def is_valid_uuid_or_404(object_uuid):
try:
return uuid.UUID(object_uuid)
except ValueError:
raise Http404("Invalid uuid")
x = Document.objects.get(uuid=is_valid_uuid_or_404(object_uuid)) #Boring
Someone has a good idea to make it better ?
EDIT 1 :
I get my object in my admin's change_view method, I override the change_view to add extra_context, this follows the recommendation of django
def change_view(self, request, object_id, form_url="", extra_context=None):
extra_context = extra_context or {}
extra_context["my_field"] = Document.objects.get(uuid=object_id).my_field
return super().change_view(request, object_id, form_url, extra_context=extra_context)