获取NameError以进行异常处理

car*_*bir 2 django error-handling django-models

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

俱乐部= Club.objects.get(ID = 8)回溯(最近通话最后一个):文件 "",1号线,在文件"/usr/local/lib/python2.7/dist-packages/django/db/models /manager.py "线131,在获取返回self.get_query_set()得到(*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))
Run Code Online (Sandbox Code Playgroud)

但它没有捕获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
Run Code Online (Sandbox Code Playgroud)

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

Dav*_*son 8

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

    except (ValueError, Club.DoesNotExist):
Run Code Online (Sandbox Code Playgroud)

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

from django.core.exceptions import ObjectDoesNotExist

...

    except (ValueError, ObjectDoesNotExist):
Run Code Online (Sandbox Code Playgroud)

作为描述在这里.