Parsing CSV with Django and csv.DictReader

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] #etc my_object = MyObject(x=X, y=Y) my_object.save() 

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.

+6
source share
2 answers

I just recently started using Django, but before I used the python csv library. When I use it, I just do the following:

 import csv ... reader = csv.reader(f) for row in reader: #do something with each row f.close() 

So you were pretty close. In addition, indexing starts at 0, so if you want to use the first element, use row[0] .

Here is more information about the csv library here . You only want to use delimiter and other options if your file format is different.

+2
source

When creating the csv file, add the header:

people.csv

 id age height 1 20 62 2 22 74 3 24 68 

 def handle_files(f): reader = csv.DictReader(open(f)) for row in reader: id=row['id'] age=row['age'] height=row['height'] my_object = MyObject(id=id, age=age,height=height) my_object.save() 
+3
source

Source: https://habr.com/ru/post/950561/


All Articles