Wednesday, April 13, 2011

what is the right way to validate if an object exists in a django view without returning 404?

basically just verify if an object exists and return the object. then based on that perform actions. I'm wondering whats the right way to do it without returning a 404?

try:
    listing = RealEstateListing.objects.get(slug_url = slug)
except:
    listing = None

if listing:
From stackoverflow
  • If you want a page to return 404 Not Found if an object doesn't exist, you can use django.shortcuts.get_object_or_404:

    listing = get_object_or_404(RealEstateListing, slug_url=slug)
    

    This will return the object with the given ID, or raise Http404 if it's not found.

    If you want to do something other than raise an Http404 exception, you could do something like this:

    try:
        listing = get_object_or_404(RealEstateListing, slug_url=slug)
    except Http404:
        # Do something else
    
    mipadi : I provided the second code snippet for that case. ;)
    Rasiel : oops.. sorry did not notice that somehow
  • I would not use the 404 wrapper if you aren't given a 404. That is misuse of intent. Just catch the DoesNotExist, instead.

    try:
        listing = RealEstateListing.objects.get(slug_url=slug)
    except RealEstateListing.DoesNotExist:
        listing = None
    
    Tiago : +1: I'd use this instead of 404 wrapper too.
    Carl Meyer : +1: Yes, this is a better solution than the accepted one, if you don't want the 404.
    Rasiel : yap, this seems to be the better solution

0 comments:

Post a Comment