2013-10-01 79 views
1

我有這個簡單的視圖功能:IndexError:字符串索引超出範圍 - Django - 爲什麼?

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

錯誤行在最後一行。

我在這裏做錯了什麼?

回答

1

爲什麼不只是做:

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異常被拋出的原因是因爲@hellsgate提到的被查詢你正在尋找的數據庫中不存在的ID。

+0

嘿布蘭登,謝謝,這看起來更酷。 render_to_response和context_instance之間的區別和請求渲染有什麼區別? – doniyor

+0

雖然這是更好的方法,但它並不能解釋錯誤發生的原因 – hellsgate

+0

render會自動爲你創建上下文實例。 – Brandon

1

錯誤實際發生在你try:

location = Location.objects.get(id=lid). 

這則觸發Location.DoesNotExist異常的第一道防線。原因是數據庫位置表中不存在.get中正在使用的位置標識。確保您的生產數據庫包含與開發數據庫相同的位置數據,包括ID,並且此錯誤將消失。

相關問題