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.
The solution I've found is that giving a
Fileobject tofilefieldand setname.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_topath of the model.A simple example code: