I am trying to upload data using Django's import-export. The export works just fine but I have been unable to import from the frontend even though the import function works just well via the default admin dashboard. Anyone with the desire to help?
views.py:
def data_upload(request):
if request.method == 'POST':
country_resource = CountryResource()
dataset = Dataset()
new_countries = request.FILES['datafile']
imported_data = dataset.load(new_countries.read())
result = country_resource.import_data(dataset, dry_run=True)
if not result.has_errors():
country_resource.import_data(dataset, dry_run=False)
return render(request, 'chainedModels/setup.html')
form:
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="datafile">
<button type="submit">Upload</button>
</form>
{% endblock %}
P.S: I also noticed that "imported_data" is being greyed out in views. When I hovered it, a popup message that "local variable 'imported_data' is not used" was displayed
EDIT:
For newbies like me who may encounter a similar issue in the future, here is how I solved it.
I created a form in forms.py to handle the file upload and then in my views.py, I did the following
def ...(request):
if request.method == 'POST':
dataform = CountryUploadForm(request.POST, request.FILES)
if dataform.is_valid():
country_resource = CountryResource()
dataset = Dataset()
file = dataform.cleaned_data['file']
import_data = dataset.load(file.read())
result = country_resource.import_data(dataset, dry_run=False)
messages.success(request, 'Data upload was successful')
return redirect('...')
else:
messages.error(request, 'Data upload error. Please choose a file')
return redirect('...')
return render(request, '...')