I have found a working app made in django. From frontend, the user can uplaod a pdf doc, then submit it, the app processes it, and then the user can access the result in the form of an excel file.
I have tried to understand the code, but I still have some questions. One of them is from what part of the code is the doc saved?
Assistant
Got it! To help you figure out where the uploaded PDF document is saved in the Django app, I’ll guide you on what to look for in the code.
Typically, in a Django app that handles file uploads, the process usually involves these steps:
Form or serializer that handles the upload — Usually a or something similar in the frontend form or API.
Great! If you have any more questions about the code or need help understanding any other parts, just let me know. Happy coding!
User
i want now to also save the uploaded file in AWS S3.
Assistant
User
from where the code inside models.py is ran?
Assistant
Great question!
When and how is the code inside models.py run in Django?
The code inside models.py files (where you define your model classes) is executed by Python when Django starts and loads your app. More specifically:
When you run a Django management command (e.g., runserver, migrate, shell, makemigrations), Django imports your app modules, including , to detect model definitions.
User
ok, so if this is the read function, then what is the write function:
Thanks for sharing this snippet! You have a MinIOConnector class (which apparently connects to an S3-compatible service like MinIO), and a called that:
User
botocore.exceptions.ClientError: n error occured (403) when calling the PutObject operation: Forbidden
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
In this case, look at that Document model’s upload_to attribute; it defines the directory path relative to your MEDIA_ROOT.
B) Saving manually to disk:
with open('some/path/to/save.pdf', 'wb+') as destination:
for chunk in uploaded_file.chunks():
destination.write(chunk)
Then check what some/path/to/save.pdf is — it could be a setting or a relative path.
What you can do now:
Search for request.FILES in your views file (views.py).
Search for .save() calls where files might be involved.
Find models with a FileField or a field handling the upload.
Check your Django settings (settings.py) for:
MEDIA_ROOT: directory where uploaded media files are stored.
MEDIA_URL: URL prefix for media files.
If you provide me with snippets from the upload handling part of the code (for example, your form, view, or model involved), I can give you a more exact explanation of where the doc is saved. Would you like to paste that part here?
tells us several important things about where and how the uploaded PDF is saved.
What does it mean?
balance_1 is a FileField: This means that uploaded files assigned to this field will be saved automatically by Django.
upload_to=user_directory_path: This means the uploaded file will be stored in a directory/path determined by the function user_directory_path.
Next steps: Check user_directory_path
upload_to can take:
A string (like 'uploads/'), which is a subdirectory under the MEDIA_ROOT.
Or a callable function, which dynamically determines the subdirectory and/or filename.
You need to find the function user_directory_path defined somewhere in your code, probably somewhere near this model or in a utils module. For example, it might look like:
def user_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
return 'user_{0}/{1}'.format(instance.user.id, filename)
The function gets two arguments:
instance — the model instance this file is attached to.
filename — original filename of the uploaded file.
It returns a relative path (relative to MEDIA_ROOT) where the file will be stored.
Location of the saved file
The physical file path will be:
<MEDIA_ROOT>/<result of user_directory_path>
You can find MEDIA_ROOT in your Django settings.py. It's typically configured like:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
So if your function returns for example user_3/mydoc.pdf, the file will be saved here:
media/user_3/mydoc.pdf
Summary
The uploaded file is saved through the balance_1 FileField.
The precise folder and filename are determined by the function user_directory_path.
The full path is <MEDIA_ROOT> + (value returned by user_directory_path).
What you should do next
Locate the definition of user_directory_path in your codebase.
Check your settings.py for MEDIA_ROOT to know the base upload folder.
If you want, paste the code of user_directory_path here, and I can explain exactly where your PDF uploads are being saved!
Got it! You want to save uploaded files to both your default Django storage (e.g., local filesystem) and AWS S3.
The typical Django + S3 setup is to replace the default storage backend with S3, but here you want to save to two places simultaneously.
How to save uploaded files both locally (default storage) and on AWS S3:
Option 1: Save once locally (default), then upload the same file explicitly to S3
You keep your existing local storage setup (using FileField and upload_to=user_directory_path), and then in your view (or signal), upload a copy of the file to S3 manually using boto3 or django-storages API.
Step-by-step approach
1. Setup AWS S3 credentials and django-storages
Make sure you have the django-storages package installed:
pip install django-storages[boto3]
In your settings.py add the AWS and storage config:
INSTALLED_APPS += ['storages']
AWS_ACCESS_KEY_ID = '<your-access-key>'
AWS_SECRET_ACCESS_KEY = '<your-secret-key>'
AWS_STORAGE_BUCKET_NAME = '<your-bucket-name>'
AWS_S3_REGION_NAME = 'your-region' # e.g. 'us-east-1'
AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com'
DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage'
# keep default as filesystem for now since you want both
# Optional S3 storage class if needed
from storages.backends.s3boto3 import S3Boto3Storage
class S3MediaStorage(S3Boto3Storage):
bucket_name = AWS_STORAGE_BUCKET_NAME
location = 'media' # prefix inside bucket (optional, can be empty)
2. Upload file manually to S3 in your view
In the view where you handle file upload (usually where you call form.save() or assign the uploaded file), add code to upload the file to S3 using the S3 storage backend or boto3.
Example:
from django.core.files.storage import default_storage
from myapp.storage_backends import S3MediaStorage # the class you defined above
def your_upload_view(request):
if request.method == 'POST':
form = YourUploadForm(request.POST, request.FILES)
if form.is_valid():
instance = form.save() # saves locally to filesystem
# Now upload the same file to S3
s3_storage = S3MediaStorage()
file_field = instance.balance_1 # This is your FileField
file_field.open() # open the file
s3_path = file_field.name # could reuse the same filename/path
# Save to s3_storage
s3_storage.save(s3_path, file_field)
file_field.close()
# continue your response or redirect
3. (Optional) Abstract it into a signal
You can also automate this with Django signals on model save, so that whenever a model instance with a file is saved, it uploads that file to S3.
Summary
Keep your existing local FileField + upload_to setup — files are saved locally as before.
After saving the model instance locally, manually save the uploaded file to AWS S3 using django-storages S3 backend or boto3.
This approach duplicates files — saved locally and remotely.
If you want, I can provide a full working example including settings, view, and storage backend class. Would that help?
models.py
When the Django app is loaded (for example, on server startup), Django runs the code in models.py to define the model classes.
What does this mean in practice?
Defining models in models.py is mostly just class definitions and function definitions; this code runs once on import.
No "active process" happens just by defining models — Django just reads the models to know what the data structures are.
The model classes are instantiated later when you create instances, query, or manipulate data.
Example:
# models.py
from django.db import models
class Document(models.Model):
balance_1 = models.FileField(upload_to=user_directory_path, blank=True, null=True)
This code is run when Django imports models.py, so the Document class is defined.
No files are saved or processed at import time!
Files are saved when you create or update instances of Document and assign a file to balance_1, then call .save().
Summary:
The code inside models.py is run on import, during the Django app load process (start-up, management commands, migrations, shell).
This defines models and registers them in Django’s internal model registry.
Actual processing, like saving files or querying, happens when your app code creates or manipulates model instances during the app execution (e.g., in views, forms, admin).
If you want, I can explain more about the Django app lifecycle or how specific model methods run when instances are created or saved!
read function
read_from_s3
Parses the s3_path,
Extracts bucket and object key,
Uses the s3_client to get the object content,
Returns a BytesIO buffer with the file content.
Your question: What would be the corresponding write function?
A "write" function would upload data to S3 / MinIO — it will likely take a file-like object (a BytesIO, file, etc.) or raw bytes and write it under a bucket/key destination.
Here is an example write function compatible with your read_from_s3 method and typical boto3 client usage:
from io import BytesIO
class MinIOConnector:
def __init__(self, s3_path: str, s3_client):
self.s3_path = s3_path
self.s3_client = s3_client
def read_from_s3(self) -> BytesIO:
path_split = self.s3_path.split("/") # e.g. s3://bucket/key
bucket = path_split[2]
key = "/".join(path_split[3:])
file_buffer = BytesIO(
self.s3_client.get_object(Bucket=bucket, Key=key)["Body"].read()
)
return file_buffer
def write_to_s3(self, data: BytesIO) -> None:
"""
Uploads the data to the S3 path.
- `data` is a BytesIO instance positioned at the start.
"""
path_split = self.s3_path.split("/")
bucket = path_split[2]
key = "/".join(path_split[3:])
# Make sure the buffer is at the start
data.seek(0)
self.s3_client.put_object(
Bucket=bucket,
Key=key,
Body=data
)
Explanation
write_to_s3 accepts a BytesIO stream (data), seeks back to the beginning, then calls put_object on the S3 client to upload the content into the target bucket/key.
The Bucket and Key are obtained from parsing the s3_path just like in read_from_s3.
This will write "Hello world!" as the contents of mybucket/myfolder/myfile.pdf.
If you want code for handling files from disk or Django file objects to upload, or want help integrating this with the rest of your app, just ask!
The botocore.exceptions.ClientError: An error occurred (403) when calling the PutObject operation: Forbidden indicates that your AWS S3 (or MinIO) client does not have permission to perform the PutObject operation on the target bucket/key.
Common causes and how to fix:
1. Incorrect IAM Permissions
The AWS credentials (access key + secret key) you're using lacks3:PutObject permission on the target bucket.
Solution: Check the IAM policy attached to the credentials. It must explicitly allow s3:PutObject on the bucket (or required prefix).
Sometimes bucket policies override or restrict access even if your IAM user/role has permission.
Ensure bucket policies don’t block writes from your credentials.
3. Wrong Credentials or Region
Make sure the credentials you use correspond to a valid user with appropriate permissions.
Also, verify your client is configured with the correct AWS region matching the bucket.
4. Using MinIO with wrong endpoint or signature version
If you use MinIO (an S3-compatible service), double-check that your s3_client is correctly configured with the right endpoint, access keys, and signature version.