首页 文章

获取NameError以进行异常处理

提问于
浏览
2

我想在页面上列出一个对象(俱乐部)细节,方法是从url中提取id并将其提供给django models api . 当数据库中存在该ID时,它正在工作 . 但是当我尝试在url中提供不存在的id时,模型api会给出这个错误:

club = Club.objects.get(id = 8)Traceback(最近一次调用最后一次):文件“”,第1行,在文件“/usr/local/lib/python2.7/dist-packages/django/db/ models / manager.py“,第131行,在get中返回self.get_query_set() . get(* args,** kwargs)文件”/usr/local/lib/python2.7/dist-packages/django/db/models /query.py“,第366行,在get%self.model._meta.object_name中)DoesNotExist:俱乐部匹配查询不存在 .

所以我在视图中为这个错误添加了一个异常处理程序 . 这是代码:

def club_detail(request, offset):
    try:
        club_id = int(offset)
        club = Club.objects.get(id=club_id)
    except (ValueError, DoesNotExist):
        raise HTTP404()
    return render_to_response('home/club_detail.html', {'club': club }, context_instance = RequestContext(request))

但它没有捕获DoesNotExist错误,而是在浏览器中给出NameError:

NameError at /club/8/
  global name 'DoesNotExist' is not defined
  Request Method:   GET
  Request URL:  http://127.0.0.1:8000/club/8/
  Django Version:   1.4.1
  Exception Type:   NameError
  Exception Value:  
  global name 'DoesNotExist' is not defined

我怎样才能让它发挥作用?提前致谢

3 回答

  • 8

    你不能直接使用DoesNotExist - 它应该是Club.DoesNotExist所以你的代码看起来像:

    def club_detail(request, offset):
        try:
            club_id = int(offset)
            club = Club.objects.get(id=club_id)
        except (ValueError, Club.DoesNotExist):
            raise HTTP404()
        return render_to_response('home/club_detail.html', {'club': club }, context_instance = RequestContext(request))
    
  • 1

    您需要导入 DoesNotExist

    from django.core.exceptions import DoesNotExist
    
  • 0

    DoesNotExist 是作为模型本身的属性实现的 . 将您的行更改为:

    except (ValueError, Club.DoesNotExist):
    

    或者,由于所有 DoesNotExist 错误都继承了 ObjectDoesNotExist 类,您可以执行以下操作:

    from django.core.exceptions import ObjectDoesNotExist
    
    ...
    
        except (ValueError, ObjectDoesNotExist):
    

    here所述 .

相关问题