2017-01-06 40 views
0

我有一個Django視圖,我通過模板中的Ajax函數調用。我的模板有'國家'下拉菜單和'區域'(或州)下拉菜單。當用戶點擊國家時,我想使用Ajax功能獲取該國的所有地區(或州),並使用該數據填充「地區」下拉菜單。然而,當我的觀點和執行試圖返回查詢集,我得到這個錯誤:爲什麼這個Django錯誤「太多的值解壓縮」?

ValueError: too many values to unpack 

這裏是模板標籤和Ajax功能:

# demo.html 
<select id="id_country" name="country" onchange="getState(this.value);"> 
    <option value="" selected="selected">Please choose...</option> 
    <option value="US">United States</option> 
    <option value="GB">United Kingdom</option> 
    <option value="CA">Canada</option> 
</select> 

<script> 
function getState(val) { 
    $.ajax({ 
    type: "GET", 
    url: "/demo/get_region", 
    data:'country_id='+val, 
    success: function(data){ 
     $("#id_region").html(data); 
    } 
    }); 
} 
</script> 

這裏是視圖:

# views.py 
from location.models import CountryRegion 
def get_region(request): 
    country_id = request.GET.get('country_id', None) 
    country_region = CountryRegion.objects.filter(country_cd=country_id) 
    # Error occurs here on the return 
    return country_region 

模型(我知道是不歸一化)看起來是這樣的:

class CountryRegion(models.Model): 
    country_cd = models.CharField(max_length=2) 
    country_name = models.CharField(max_length=50) 
    region_cd = models.CharField(max_length=3) 
    region_name = models.CharField(max_length=50) 

數據庫記錄是這樣的:

id country_cd country_name region_cd region_name 
59 US   United States NY   New York 

爲什麼這個錯誤發生?如果國家代碼是'美國',我會 返回50個實例,每個州有一個實例。 Django視圖可以返回的數據量有限制嗎?

+0

[Django的視圖返回JSON的可能的複製沒有使用模板](http://stackoverflow.com/questions/9262278/django-view-returning-json-without-using-template) –

+3

你應該返回一個'Response'對象而不是'CountryRegion'對象。請參閱https://docs.djangoproject.com/en/1.10/topics/http/views/ – Gocht

回答

0

,你必須先導入JSON,
進口JSON
然後
返回的HttpResponse( json.dumps(country_region), CONTENT_TYPE = 「應用/ JSON」 )

相關問題