Refactorized code with get_object_or_404 function