I am trying to implement a simple xls file import and save to a model using django-import-export. Unfortunately the docs only cover the admin integration. I am stuck here in my example code:
class UploadFileForm(forms.Form):
file = forms.FileField()
class ExportSpec(resources.ModelResource):
class Meta:
model = Specialty
view:
def ca_import(request):
if request.method == 'POST' and 'import_test' in request.POST:
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
filehandle = request.FILES['file']
dataset = ???
result = ExportSpec().import_data(dataset, dry_run=False,
raise_errors=True,
user=request.user)
Can someone with understanding of this module help me complete the code for this generic example?
Or is there a generic example snipped somewhere on the net which I did not find using google?
EDIT:
Based on Alex answer I was able to find a working solution:
def ca_import(request):
if request.method == 'POST' and 'import_test' in request.POST:
form = 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 = ExportSpec().import_data(dataset, dry_run=False, raise_errors=True, user=request.user)
You should use the Format.create_dataset()
method:
from import_export.formats.base_formats import XLS
def your_view():
filehandle = form.cleaned_data['file']
data = bytes()
for chunk in import_file.chunks():
data += chunk
dataset = XLS().create_dataset(data)
result = ExportSpec().import_data(...)
来源:https://stackoverflow.com/questions/34739370/django-import-export-outside-admin