I have a Django model that has a FileField, the file has to be saved in AWS S3.
models.py:
class Search(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='searches')
type = models.CharField(max_length=150)
keyword = models.CharField(max_length=150)
amount = models.IntegerField()
date = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=50)
results = models.FileField(blank=True, storage=PrivateMediaStorage())
The upload to AWS S3 works when I create a new object in the admin area and upload a file there. However, I want to create a CSV file in the backend and upload it to S3 from there, not using any form.
Inside the backend function:
with open(f'results{search_id}.csv', 'w', newline='') as f:
writer = csv.writer(f)
header = ['name', 'email', 'follower_count', 'play count', 'share count', 'comment count', 'has email']
writer.writerow(header)
for result in results:
data = [result['author_name'], result['author_email'], result['follower_count'], result['play_count'], result['share_count'], result['comment_count'], result['has_email']]
writer.writerow(data)
# Updating database data
search = Search.objects.get(id=search_id)
search.status = 'Finished'
search.results = ContentFile(f)
search.save()
However, right now this just creates a results.csv file in my Django directory and doesn't upload any file to S3. How can I fix this?