Home > Enterprise >  Accessing TemporaryFilePath in form_valid Django
Accessing TemporaryFilePath in form_valid Django

Time:10-09

Currently my users are able to upload files, as I am deployed via Heroku I am using Django-storages to upload to AWS S3 buckets. I am using a CreateView/UpdateView as below, this works well however I now want to be able to run an operation on the file before uploading to AWS, my research insofar suggests that I can use temporary_file_path() to do this in the form_valid however I am getting an error, UpdateView/CreateView

class project_update(LoginRequiredMixin, UpdateView):
    model = Project
    form_class = ProjectForm
    template_name = "home/update_project.html"
    context_object_name = 'project'
    success_url = reverse_lazy("project-list")
    def form_valid(self, form):
        handle_uploaded_boq(form['boq_file'].temporary_file_path(), form.cleaned_data['project_title'])
        return super(project_update, self).form_valid(form)

However I am getting the following error:

'BoundField' object has no attribute 'temporary_file_path'

So what is the best way to run the operation handle_uploaded_boq() before the file is uploaded to AWS?

CodePudding user response:

to access the file in form_valid method you can use

form.files['boq_file']

and to access the path of uploaded file of TemporaryUploadedFile class, use

form.files['boq_file'].temporary_file_path()    

or

form.files['boq_file'].file.name

Note: to get the path of the uploaded file, the uploaded file must be an object of class TemporaryUploadedFile and not of InMemoryUploadedFile. You can handle it by updating the FILE_UPLOAD_HANDLERS in setting.py to following

FILE_UPLOAD_HANDLERS = [
    'django.core.files.uploadhandler.TemporaryFileUploadHandler',
]

assuming that the name of file_field you used in the form is boq_file

  • Related