How to save a file to a django model's filefield so that django handle the upload_to things?

2.4k Views Asked by At

I need to compose a file in views.py, and set the file to filefield in a createView. Here is how my code looks:

models.py:

    class A(models.Model):
        data = models.CharField()
        file = models.FileField(upload_to='%Y/%m/%d/', blank=True, null=True)

views.py:

    class ACreateView(CreateView):

        def form_valid(self, form):
            new_file_path = compose_a_new_file() ## make new file saved somewhere.
            form.instance.file.path = new_file_path 
            result = super().form_valid(form)
            return result 

Here, new_file_path is the path of newly composed and saved in a folder.

I just want to fill the file filefield with the newly composed file, and save it to the path defined by upload_to='%Y/%m/%d/'. (just as if I've uploaded by POST method from client)

But the code above didn't save the file into '%Y/%m/%d/' folder.

How can I get that? Any advice would be grateful.

1

There are 1 best solutions below

1
On

The solution I've found is that giving a File object to filefield and set name.

This way, django will handle the filefield as if it was uploaded from client web browser using POST method; django will save the file to upload_to path of the model.

A simple example code:

from django.core.files import File

class ACreateView(CreateView):

    def form_valid(self, form):

        form.instance.file = File(open(filename)) 
        form.instance.file.name = filename        
  
        result = super().form_valid(form)
        return result