views:

885

answers:

2

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:
+3  A: 

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. ;)
mipadi
oops.. sorry did not notice that somehow
Rasiel
+10  A: 

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
ironfroggy
+1: I'd use this instead of 404 wrapper too.
Tiago
+1: Yes, this is a better solution than the accepted one, if you don't want the 404.
Carl Meyer
yap, this seems to be the better solution
Rasiel