我需要 Django 管理界面来接受管理员上传的 Excel 文件,其中每个 Excel 文件中的数据都被插入到我的数据库模型中。我怎样才能使这样一个“上传”按钮出现在 Django 模型管理页面上,单击该按钮要求管理员选择一个 .xls
文件,一旦上传完成,其数据就会被添加到数据库中完成了吗?
最佳答案
我已经这样做了,但我只是设置了一个带有文件上传的简单 View (实际上这比将它直接添加到 Django 管理页面更有意义,因为一个编辑页面 = 一个模型实例,我假设你的excel 包含多个模型)。
在 forms.py 中,一个带有文件上传字段的简单表单
class ImportExcelForm(forms.Form):
file = forms.FileField(label= "Choose excel to upload")
在 views.py 中,处理上传的 View
def test_flowcell(request):
c = RequestContext(request, {'other_context':'details here'})
if request.method == 'POST': # If the form has been submitted...
form = ImportExcelForm(request.POST, request.FILES) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
excel_parser= ExcelParser()
success, log = excel_parser.read_excel(request.FILES['file'] )
if success:
return redirect(reverse('admin:index') + "pages/flowcell_good/") ## redirects to aliquot page ordered by the most recent
else:
errors = '* Problem with flowcell * <br><br>log details below:<br>' + "<br>".join(log)
c['errors'] = mark_safe(errors)
else:
c['errors'] = form.errors
else:
form = ImportExcelForm() # An unbound form
c['form'] = form
return render_to_response('sequencing/file_upload.html')
并且正如另一篇文章中所建议的那样,使用 xlrd 从 excel 文件中读取数据。为此,我有一个单独的文件 ExcelParser.py
import xlrd
class ExcelParser(object, excel_name):
@transaction.commit_on_success
def read_excel(self):
wb = xlrd.open_workbook(excel_name)
...
do your parsing in here.....
...
(我可以补充一点,Excel 是一种糟糕且容易出错的数据导入方式。我在工作中经常使用它,并试图说服管理层有更好的解决方案。)
关于python - 通过 django admin 将 excel 数据导入模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9983001/