python - 通过 django admin 将 excel 数据导入模型

标签 python django django-admin xls

我需要 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/

相关文章:

python - 连接到网页的脚本

python - 使用 Python 规范化空格

django - 在 Django : when to use save() vs chunks() vs cleaned_data? 中处理图像上传表单

Django、ModelForms、User 和 UserProfile - 不散列密码

python - 如何将自定义部分添加到 Django 管理主页?

javascript - 当用户登录时,django 中是否有可能将用户主动登录的浏览器名称存储在数据库中?

python - 从Amazon S3读取仅具有特定名称的文件

python:几何布朗运动模拟

python - 如何在模板中获取 ImageField URL?

python - Django-admin:TemplateDoesNotExist 位于/admin/plans/plan/