2

I need to process an uploaded file with GeoDjango. According to the documentation, I should use Datasource() constructor from GDAL.

Problem is that size of uploaded shapefiles can be less than 2.5 MB, so MemoryFileUploadHandler is used by default and thus I can't access to a filepath required by Datasource().

I decided to override request.upload_handlers for my specific view, with only "django.core.files.uploadhandler.TemporaryFileUploadHandler" because I don't need to create a subclass (for now), but I get the following error : You cannot set the upload handlers after the upload has been processed.

Here is my piece of code:

def home(request):
    request.upload_handlers = ["django.core.files.uploadhandler.TemporaryFileUploadHandler"]

    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])
    else:
        form = UploadFileForm()
    return render(
        request,
        'app/index.html',
        {
            'title':'HOME',
            'form': form,
        }
    )

What am I doing wrong ? Also, should I create a subclass for a custom handler anyway ?

Beinje
  • 572
  • 3
  • 18

1 Answers1

1

the problem is when the function is called django already use the upload_handler so it's to late to change it.

I remember you might be able to still change it if you disable csrf for the function. (Also see: Where/how to replace default upload handler in Django CBV?)

Another possibility would be writing your own upload handler or maybe a middleware that changes the upload handler depending on the path.

Bastian
  • 10,403
  • 1
  • 31
  • 40
  • Thanks for the pointer ! Regarding your proposal to write my own upload handler, does it mean I should add it in `settings.py` in the list of default handler ? Or should I specify it in my view. If so, the csrf module would still complain about me trying to set the handler after it get called, right ? – Beinje Feb 19 '20 at 10:24