[Fixed]-Django upload for processing

1👍

Use a Form:

class UploadForm(forms.Form):

    file = forms.FileField()

    def process(self):
        file = self.cleaned_data.get('file')
        # do whatever you need here to process the file
        # e.g. data = file.read()

In your view, call process() on your form after the user uploads the file and the form is successfully validated.

def my_view(request):
    if request.method == 'POST':
        form = UploadForm(files=request.FILES)
        if form.is_valid():
            form.process()
            return ...

Depending on the size of the file and your Django settings for FILE_UPLOAD_HANDLERS, the file is discarded immediately after the view is done processing if MemoryFileUploadHandler is used. The operating system will also eventually discard the file if TemporaryFileUploadHandler is used.

Leave a comment