[Answer]-How to add a variable in views context DJANGO?

1👍

About identation, you need to use 4 spaces to program Python.

Try this:

from django.shortcuts import render, render_to_response, RequestContext
import csv

def get_data():
    with open('test.csv', 'rb') as csvfile:
        a = []
        spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
        for row in spamreader:
            a.append(row)
        return {'csvdata': a}

def home(request):
    return render_to_response('home.html', get_data(), context_instance=RequestContext(request))

Then you should be able to call a with csvdata name in template.

👤Gocht

0👍

The problem is that a is a name in the global scope and therefore isn’t a part of locals(). Instead of locals(), explicitly pass the arguments you need for the template (e.g. a).

0👍

from django.shortcuts import render, render_to_response, RequestContext
import csv

def home(request):
    with data as csv.reader( open('myfile.csv', 'r'), delimiter=','):
        return render_to_response('home.html', {'data': data}, context_instance=RequestContext)

data in the code I wrote should contain a list of rows.

Leave a comment