[英]IndexError: string index out of range - Django - Why?
我有这个简单的查看功能:
def location(request,locname,lid):
try:
location = Location.objects.get(id=lid)
return render_to_response('location.html',{'location':location},context_instance=RequestContext(request))
except Location.DoesNotExist:
return render_to_response('404.html',{},context_instance=RequestContext(request)) #<-- error line
但是我只在生产服务器上得到IndexError: string index out of range
。
错误行在最后一行。
我在这里做错了什么?
该错误实际上是在try:
块的第一行中发生的
location = Location.objects.get(id=lid).
然后,这将触发Location.DoesNotExist
异常。 这样做的原因是.get
中使用的位置ID在数据库位置表中不存在。 确保生产数据库包含与开发数据库相同的位置数据,包括ID,并且此错误将消失。
为什么不做:
from django.shortcuts import render, get_object_or_404
from your_app.models import Location
def get_location(request, lid):
location = get_object_or_404(Location, id=lid)
return render(request, 'location.html', {'location': location})
之所以会抛出DoesNotExist
异常,是因为您要查找的ID在查询@hellsgate所提到的数据库中不存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.