I building a website using Django and I would like to create a functionality in which an user via an excel sheet can upload information and populate the database. So I install the django-excel package and follow the example:
settings.py:
FILE_UPLOAD_HANDLERS = ("django_excel.ExcelMemoryFileUploadHandler",
"django_excel.TemporaryExcelFileUploadHandler")
urls.py:
url(r'^import_sheet/', views.import_sheet, name="import_sheet"),
views.py:
class UploadFileForm(forms.Form):
file = forms.FileField()
def upload(request):
if request.method == "POST":
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
filehandle = request.FILES['file']
return excel._make_response(filehandle.get_sheet(),"xslx",file_name="download")
else:
form = UploadFileForm()
return render(request,'upload_form.html',{
'form': form,
'title': 'Excel file upload',
'header': 'Please choose a valid excel file'
})
def import_sheet(request):
if request.method == "POST":
form = UploadFileForm(request.POST,
request.FILES)
if form.is_valid():
request.FILES['file'].save_to_database(
model= quote_input,
mapdict= ["value_date", "value", "type", 'name'])
return HttpResponse("OK")
else:
return HttpResponseBadRequest()
else:
form = UploadFileForm()
return render(
request,
'upload_form.html',
{'form': form})
models.py:
class quote_input(models.Model):
value_date = models.DateField()
value = models.FloatField()
type = models.TextField(max_length=254)
name = models.TextField(max_length=254)
# link
fund = models.ForeignKey(Fund)
benchmark = models.ForeignKey(Benchmark)
factor = models.ForeignKey(Factors)
stress_factor = models.ForeignKey(Stress_Factors)
When I try this code by uploading a basic excel sheet:
I got an OK (HttpResponse) but when I looked at the database, I have uploaded nothing.
Does someone have the same problem? or can provide another example that I can use? another methodology?
Another question: within the django-excel documentation, there is a reference about a function "choice_func" which is defined as a custom formatting function. Can anyone provide more information about this function?
Here's a version of my code, I use xlrd library.
And the view:
And the template: