Is there any way to append directly to a FileField in django? Doing something like this:
class ChunkedUpload(models.Model):
id = models.CharField(max_length=128)
data = models.FileField(upload_to='chunked_uploads/')
def append_chunk(self, chunk, create):
if create:
self.data.save(self.id, ContentFile(chunk.encode()))
else:
self.data.append(ContentFile(chunk.encode())
I'm working on an existing solution that sent data by chunks (base64 encoded string) in TextField. But some data are now too big to be handled in a TextField (250++ Mb). I can't change the other parts of the application, so I'm trying to find a way to handle this situation.
Answer from Chatbot GPT:
# 1. Create a FileField in your model:
class MyModel(models.Model):
my_file = models.FileField(upload_to='files/')
# 2. Create a function to append to the file:
def append_to_file(file_field, data):
with open(file_field.path, 'a') as f:
f.write(data)
# 3. Call the function with the FileField and the data you want to append:
append_to_file(my_model.my_file, 'This is the data I want to append.')