我正在使用django-import-export库来导入和导出xls格式,一切都可能在AdminModel上正常工作,现在我正在尝试使用views.py和template进行导入,但是由于某些原因无法正常工作和我一起
views.py
def simple_upload(request):
if request.method == 'POST':
person_resource = resources.SimsResource()
dataset = Dataset()
new_persons = request.FILES['myfile']
imported_data = dataset.load(new_persons.read())
result = person_resource.import_data(dataset, dry_run=True) # Test the data import
if not result.has_errors():
person_resource.import_data(dataset, dry_run=False) # Actually import now
return render(request, 'import_sims.html', {'errors': result.has_errors(), 'result': result})
return render(request, 'import_sims.html')
resources.py
class SimsResource(resources.ModelResource):
class Meta:
model = models.Sim
fields = ['s_serial_number', 's_number', 's_provider', 'status']
forms.py
class UploadFileForm(forms.Form):
file = forms.FileField()
url.py
url(r'^importing_sims/$', views.simple_upload, name='Import'),
模板
{% if errors %}
errors:
{{ errors }}
<br><br><br>
resluts :
{{ result }}
{% endif %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="myfile">
<button type="submit">Upload</button>
</form>
和错误输出:
errors: True
resluts : <import_export.results.Result object at 0x1072b75f8>
更新:
在views.py中进行一些更新后,这是新错误:
KeyError at /importing_sims/
'id'
未在管理员导入中显示
这是更新:
def simple_upload(request):
if request.method == 'POST':
form = forms.UploadFileForm(request.POST, request.FILES)
if form.is_valid():
file = form.cleaned_data['file']
data = bytes()
for chunk in file.chunks():
data += chunk
dataset = XLS().create_dataset(data)
result = resources.SimsResource().import_data(dataset, dry_run=False, raise_errors=True, user=request.user)
return render(request, 'import_sims.html', {'errors': result.has_errors(), 'result': result})
return render(request, 'import_sims.html')