Django / Python捕获异常不起作用?

时间:2011-04-20 11:02:27

标签: python django exception

这段代码不能正常工作吗?

    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"

类别是IntegerField。当用户输入类别没有值的URL http://myurl.com?category=时,我正在尝试处理这种情况。

感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

尝试这样的事情:

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

答案 1 :(得分:2)

如果未设置if语句,则request.GET.get将返回无。

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