【问题标题】:How to send an object back to Django view and access it by indexing如何将对象发送回 Django 视图并通过索引访问它
【发布时间】:2017-07-13 15:28:10
【问题描述】:

在我的 HTML 中,我有一个对象 data。数据最初是从 views.py 中的 Django 中的 SQL 查询中检索到的,并使用 render() 传递给 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,所以将 data 发送回 views.py(我使用 this question 创建 csrftoken)

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

如何向 Django 发送数据,以便我可以使用 data[0]['pk'] 在views.py 中访问它?

【问题讨论】:

    标签: python django


    【解决方案1】:

    我自己想通了。

    首先您需要将对象解析为 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
    

    【讨论】:

      猜你喜欢
      • 2017-04-15
      • 2016-01-17
      • 1970-01-01
      • 2019-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-13
      • 1970-01-01
      相关资源
      最近更新 更多