0

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!

3
  • No, it doesn't work. It has an indentation error ;) Commented Apr 20, 2011 at 11:06
  • Thanks for your reply. If you're talking about the if indentation and the code inside it, it's correct on my IDE. SO doesn't like to paste indentations correctly... Commented Apr 20, 2011 at 11:16
  • 3
    "SO doesn't like to paste indentations correctly". That's always been false in my experience. Odds are good you still have something else wrong like mixed tabs and spaces. Commented Apr 20, 2011 at 11:32

2 Answers 2

3

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"
Sign up to request clarification or add additional context in comments.

1 Comment

+1, i think it's better to just do : category = request.GET.get("category") and by default category will be None if it's not in the dictionary.
2

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.."

2 Comments

I take that back. I got a int() argument must be a string or a number, not 'NoneType' without the if
ah, right.. that's a TypeError, not ValueError; edited the answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.