I am new to django.I want upload the csv file,process the data and render the results it on UI.For that I have created the following code. The problem is csv file is not uploading. If I'm uploaded other file format it not showing any error message. Also I want to print csv data the results on UI. views.py
from django.shortcuts import render
from django.conf import settings
from django.http import HttpResponseRedirect
from django.contrib import messages
import csv
from django.core.urlresolvers import reverse
import logging
def upload_csv(request):
data = {}
if "GET" == request.method:
return render(request, "myapp/upload_csv.html", data)
# if not GET, then proceed
try:
csv_file = request.FILES["csv_file"]
if not csv_file.name.endswith('.csv'):
c=messages.error(request,'File is not CSV type')
return HttpResponseRedirect(reverse("myapp:upload_csv",{"c":c}))
#if file is too large, return
if csv_file.multiple_chunks():
messages.error(request,"Uploaded file is too big (%.2f MB)." % (csv_file.size/(1000*1000),))
return HttpResponseRedirect(reverse("myapp:upload_csv"))
file_data = csv_file.read().decode("utf-8")
lines = file_data.split("\n")
#loop over the lines and save them in db. If error , store as string and then display
for line in lines:
fields = line.split(",")
data_dict = {}
data_dict["GSTIN/UIN"] = fields[0]
data_dict["start_date_time"] = fields[1]
data_dict["end_date_time"] = fields[2]
data_dict["notes"] = fields[3]
try:
form = EventsForm(data_dict)
if form.is_valid():
form.save()
else:
logging.getLogger("error_logger").error(form.errors.as_json())
except Exception as e:
logging.getLogger("error_logger").error(repr(e))
pass
except Exception as e:
logging.getLogger("error_logger").error("Unable to upload file. "+repr(e))
messages.error(request,"Unable to upload file. "+repr(e))
#return HttpResponseRedirect(reverse("myapp:index",data_dict))
return HttpResponseRedirect("myapp/upload_csv.html")
html
<html> <form action="{% url "myapp:upload_csv" %}" method="POST" enctype="multipart/form-data" class="form-horizontal"> {% csrf_token %} <div class="form-group"> <label for="name" class="col-md-3 col-sm-3 col-xs-12 control-label">File: </label> <div class="col-md-8"> <input type="file" name="csv_file" id="csv_file" required="True" class="form-control"> </div> </div> <div class="form-group"> <div class="col-md-3 col-sm-3 col-xs-12 col-md-offset-3" style="margin-bottom:10px;"> <button class="btn btn-primary"> <span class="glyphicon glyphicon-upload" style="margin-right:5px;"></span>Upload </button> </div> </div> <p><input type="submit" value="Upload" /></p> {% if c %} <p> {{c}} <p> {% endif %} </form> </html>
Also help me to print the csv data on UI
You need to be passing data to you html file via the context. You'll need to amend your code something like.
rows = []
lines = file_data.split("\n")
#loop over the lines and save them in db. If error , store as string and then display
for line in lines:
fields = line.split(",")
data_dict = {}
data_dict["GSTIN/UIN"] = fields[0]
data_dict["start_date_time"] = fields[1]
data_dict["end_date_time"] = fields[2]
data_dict["notes"] = fields[3]
try:
form = EventsForm(data_dict)
if form.is_valid():
form.save()
else:
logging.getLogger("error_logger").error(form.errors.as_json())
except Exception as e:
logging.getLogger("error_logger").error(repr(e))
pass
rows.append(line)
except Exception as e:
logging.getLogger("error_logger").error("Unable to upload file. "+repr(e))
messages.error(request,"Unable to upload file. "+repr(e))
variables = {}
variables['lines'] = rows
#return HttpResponseRedirect(reverse("myapp:index",data_dict))
return render(request,"myapp/upload_csv.html", variables)
Then in the html file
<table>
{% for line in lines %}
<tr><td>{{ line.0 }}</td><td>{{ line.1 }}</td></tr>
{% endfor %}
</table>
There might be a couple of typos in here but it should set you in right direction
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.