开发者

Django / Python catch exception not working?

开发者 https://www.devze.com 2023-02-27 01:30 出处:网络
Should this code not be working? if request.GET.has_key(\"category\"): try: post_list = post_list.filter(category=request.GET.get(\"category\"))

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

精彩评论

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

关注公众号