简体   繁体   English

在Django View中传递列表或数组(作为参数)

[英]Passing list or array (as parameter) in Django View

How to use the passed value (list/array) in Django View? 如何在Django View中使用传递的值(列表/数组)? I have tried something like this: 我已经尝试过这样的事情:

def to_csv(request):
    g_data = request.GET.getlist('json_data')
    g_header = request.GET.get('header')
    g_info = request.GET.get('info')
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'

    list_header = [[g_info, '', '', '', '', '', '', ''],
                   ['Municipality', 'Barangay', 'Total Number of Structures', 'Total Not Affected', 'Total Affected',
                    'Low', 'Medium', 'High', 'Total Affected %']]
    disclaimer = [
        'Disclaimer: The information....',
        '', '', '', '', '', '']

    for val in g_data:
        perc = (val[4] / float(val[2])) * 100
        st_perc = str(round(perc, 2))
        val.append(st_perc)
        list_header.append(val)

    list_header.append(disclaimer)

    writer = csv.writer(response)
    writer.writerows(list_header)
    return response

and in my JavaScript code using AJAX: 并在我的JavaScript代码中使用AJAX:

function to_csv(json_data, header, info){
 $.ajax({
    url: "/to_csv/",
    headers: {
    Accept : "text/csv; charset=utf-8",
    "Content-Type": "text/csv; charset=utf-8"
    },
    type: "GET",
    data: {
        'json_data': json_data,
        'header': header,
        'info':info
    },

The problem is, it does not get the passed data ( g_data ) 问题是,它不获取传递的数据( g_data

It seems a waste of a round trip to send your data to the server and ask it to create a CSV when you can quite easily do that in the javascript itself. 当您可以很轻松地在javascript本身中执行此操作时,将数据发送到服务器并要求它创建CSV似乎很浪费时间。 Less load on the server, faster response. 服务器上的负载更少,响应速度更快。

Assuming your link is like 假设您的链接就像

<a href="" id="download_link">Download CSV</a>

Then 然后

function to_csv(json_data, header, info){
    var s = "data:text/csv,"
    for (var key in json_data) {
        if (json_data.hasOwnProperty(key)) {
            s += json_data[key];
        }
    }
}

通过使用json.loads解决了这个问题:

g_data = json.loads(request.GET.get('json_data'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM