Search code examples
csvdjango-rest-frameworkdjango-import-export

Import csv file in drf


I'm trying to create a view to import a csv using drf and django-import-export.

My example (I'm doing baby steps and debugging to learn):

class ImportMyExampleView(APIView):
    parser_classes = (FileUploadParser, )

    def post(self, request, filename, format=None):
        person_resource = PersonResource()
        dataset = Dataset()
        new_persons = request.data['file']
        imported_data = dataset.load(new_persons.read())
        return Response("Ok - Babysteps")

But I get this error (using postman):

Tablib has no format 'None' or it is not registered.

Changing to imported_data = Dataset().load(new_persons.read().decode(), format='csv', headers=False) I get this new error:

InvalidDimensions at /v1/myupload/test_import.csv
No exception message supplied

Does anyone have any tips or can indicate a reference? I'm following this site, but I'm having to "translate" to drf.


Solution

  • Starting with baby steps is a great idea. I would suggest get a standalone script working first so that you can check the file can be read and imported.

    If you can set breakpoints and step into the django-import-export source, this will save you a lot of time in understanding what's going on.

    A sample test function (based on the example app):

    def test_import():
        with open('./books-sample.csv', 'r') as fh:
            dataset = Dataset().load(fh)
        book_resource = BookResource()
        result = book_resource.import_data(dataset, raise_errors=True)
        print(result.totals)
    

    You can adapt this so that you import your own data. Once this works OK then you can integrate it with your post() function.

    I recommend getting the example app running because it will demonstrate how imports work.

    InvalidDimensions means that the dataset you're trying to load doesn't match the format expected by Dataset. Try removing the headers=False arg or explicitly declare the headers (headers=['h1', 'h2', 'h3'] - swap in the correct names for your headers).