开发者

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!


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"


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜