rabbid
rabbid

Reputation: 5725

Django / Python catch exception not working?

Should this code not be working?

    if request.GET.has_key("category"):
        try:
            post_list = post_list.filter(category=request.GET.get("category"))
        except ValueError:
            print "Category is not an integer"

Category is an IntegerField. I'm trying to handle the case when a user enters the URL http://myurl.com?category= where category has no value.

Thanks for your help!

Upvotes: 0

Views: 1883

Answers (2)

vartec
vartec

Reputation: 134691

No need for the if statement, request.GET.get will return None if it's not set.

try:
    post_list = post_list.filter(category=int(request.GET.get("category")))
except ValueError:
    print "Category is not an integer"
except TypeError:
    print "no Category passed.."

Upvotes: 2

dting
dting

Reputation: 39297

Try something like this:

category = request.GET.get("category")
if category:
    try:
        post_list = post_list.filter(category=int(category))
    except ValueError:
        print "That's not an integer"

Upvotes: 3

Related Questions