Hamiltonian dynamics and constrained variational calculus: continuous and discrete settings