我使用 Django 构建了一个网站,我想创建一个功能,用户可以通过 Excel 工作表上传信息并填充数据库。所以我安装了 django-excel 包并按照示例进行操作:
设置.py:
FILE_UPLOAD_HANDLERS = ("django_excel.ExcelMemoryFileUploadHandler",
"django_excel.TemporaryExcelFileUploadHandler")
urls.py:
url(r'^import_sheet/', views.import_sheet, name="import_sheet"),
视图.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})
模型.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)
我得到了 OK (HttpResponse),但是当我查看数据库时,我什么也没上传。
有人有同样的问题吗?或者可以提供另一个我可以使用的例子?另一种方法?
另一个问题:在 django-excel 文档中,有一个关于函数“choice_func”的参考,该函数被定义为自定义格式化函数。谁能提供有关此功能的更多信息?