Skip to content

Instantly share code, notes, and snippets.

@imkevinxu
Created August 16, 2012 02:11
Show Gist options
  • Select an option

  • Save imkevinxu/3365661 to your computer and use it in GitHub Desktop.

Select an option

Save imkevinxu/3365661 to your computer and use it in GitHub Desktop.
Django code to read uploaded CSV file
<form action="{% url %}" method="post" enctype="multipart/form-data">{% csrf_token %}
<input type="file" name="csv_file" />
<input type="submit" value="Upload" />
</form>
def index(request):
if request.POST and request.FILES:
csvfile = request.FILES['csv_file']
dialect = csv.Sniffer().sniff(codecs.EncodedFile(csvfile, "utf-8").read(1024))
csvfile.open()
reader = csv.reader(codecs.EncodedFile(csvfile, "utf-8"), delimiter=',', dialect=dialect)
return render(request, "index.html", locals())
@isaacbendel

Copy link
Copy Markdown

For us newbies...
Note that you have to;
import csv
import codecs

@sooraj771989

Copy link
Copy Markdown

Can you help me with code for reading xml file

@4rshdeep

4rshdeep commented Jun 3, 2017

Copy link
Copy Markdown

How to use this?

@lopezayl

lopezayl commented Jul 6, 2017

Copy link
Copy Markdown

Tried this, but using "import csv" caused ALL links to views in that views.py file to be treated as download links (i.e. clicking on a link that corresponds to a view in that views.py file results in the HTML code for that view to be downloaded).

@exisz

exisz commented Sep 3, 2018

Copy link
Copy Markdown

@lopezayl
Not sure if that will be the case, but if that really happens you have to "import csv" from within the views.

@nesazeri

Copy link
Copy Markdown

fails...

@tripathick

Copy link
Copy Markdown

fails

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment