How to import data from csv/xls file in database using python django
def import_data(request):
log_message= None
if request.method == 'POST':
file_name=request.FILES['csv_file'].name
fname=str(time.time())+'-'+file_name
handle_uploaded_file( request.FILES['csv_file'] , 'upload/'+fname)
with open('upload/'+fname) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
p = Product( product_name=row['product_name'], price=row['price'], content_text=row['content_text'] )
p.save()
log_message = 'Data has been successfully added'
product_list = Product.objects.order_by('-pub_date')
context = {'product_list': product_list , 'message': log_message}
return render(request,'administrator/dashboard.html',context)
def handle_uploaded_file(f,fnam):
destination = open(fnam, 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
======================================================================================
def import_data(request):
import csv
import pyexcel.ext.xls
log_message= None
if request.method == 'POST':
file_name=request.FILES['csv_file'].name
extension = filename.split(".")[1]
sheet = pyexcel.get_sheet(file_type=extension, file_content=request.FILES['csv_file'].read())
for row_xls in sheet:
if row_xls[0] == 'name':
continue
print row_xls[0]
return HttpResponse()
fname=str(time.time())+'-'+file_name
handle_uploaded_file( request.FILES['csv_file'] , 'upload/'+fname)
with open('upload/'+fname) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
p = Product( product_name=row['product_name'], price=row['price'], content_text=row['content_text'] )
p.save()
log_message = 'Data has been successfully added'
product_list = Product.objects.order_by('-pub_date')
context = {'product_list': product_list , 'message': log_message}
return render(request,'administrator/dashboard.html',context)
def handle_uploaded_file(f,fnam):
destination = open(fnam, 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()