I have a Django model with many fields (about 24), and apparently my users would like to be able to instantiate this object using a spreadsheet, instead of manually entering all the data into the forms.
I found that using python built-in to the CSV module should make it pretty simple, but it's hard for me to determine how to use it exactly.
Let's start with what I have in terms of code:
def upload_file(request): if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): handle_files(request.FILES['file']) return HttpResponseRedirect('/workflow/') else: print form.errors print request.FILES return HttpResponseRedirect('/workflow/upload') else: form = UploadFileForm() return render(request, 'fileform.html', {'formset': form})
This takes the CSV file as a downloadable file and passes it to handle_files to handle parsing and creating the object. This is the method I'm having problems with.
def handle_files(f): reader = csv.DictReader(f, delimiter=' ', quotechar='|') ...
I tried to imitate python docs ( http://docs.python.org/2/library/csv.html ), but DictReader is very poorly documented. Do I provide csv.DictReader() with the appropriate arguments? If I have, how can I get information from the reader ? I am going to provide a template for users, so I can assume that each column of the CSV file has predictable data. That is, I know that column A will have data corresponding to field X, and column B will correspond to Y, etc. How can I parse data from the reader and then create an object with this data?
I assume it will be something like:
for row in reader: X=row[1] Y=row[2]
Is it so? Should I use a different type of CSV reader?
Thanks for any help, I know there are a lot of questions in this post.