0

How to use the passed value (list/array) in 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:

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)

0

2 Answers 2

1

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. 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];
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Solved this by using json.loads:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.