2017-07-12 71 views
0

在我的HTML對象送回Django的查看和訪問它,我有data。數據最初是從views.py在Django一個SQL查詢中使用渲染獲取並傳遞到HTML()如何通過索引

對象

data看起來像這樣

data1= { 
     0:{ 
      pk:1, 
      model:"binaryQuestionApp.painting", 
      fields: {title:'Pearl',artist:"vermeer"}, 
     }, 
     1:{ 
      pk:2, 
      model:"binaryQuestionApp.painting", 
      fields: {title:'Sand',artist:"vermeer"}, 
     } 
    } 

我用下面的JS所以送dataviews.py(我創建csrftoken使用this question

function post_data() { 
    var postdata = { 
     'data': data, 
     'csrfmiddlewaretoken': csrftoken 
    }; 
    $.post('', postdata); // POST request to the same view I am now 
}; 

現在,數據正在發送回服務器,但我無法訪問它。我有這個在我的views.py

if request.method == 'POST': 
    data = request.POST 
    # so far it works. But i can not index like this: 
    print(data[0]['pk'] 
    # instead I need to index it strangely, like this: 
    print(data['data[0][pk]']) # note the entire key is a string 

如何使用數據[0] [「PK」]我將數據發送到Django的,這樣我可以訪問它在views.py

回答

0

我想出了自己。

首先您需要將對象解析爲JSON。

var postdata = { 
    data: JSON.stringify(data), 
    'csrfmiddlewaretoken': csrftoken 
}; 

然後postdata可以使用發送(注意$,這使用jQuery的)

$.post('', postdata); // POST request to the same view I am now 

在服務器端,在views.py您需要使用get()方法:

import json 
def index(request): 

    if request.method == 'POST': 
     data = request.POST.get('data') 
     data = json.loads(data) 
     print(data[0]['model']) # this indexing will depend on your own setup, works just like any python dict