Iam writing a webapp to help user create invoices. I manage to create and save the pdfs but I cannot get django_sendfile2 to save them.
This is my django model with the upload_to function:
def claim_path(instance, filename):
return "archive/{0}_{1}/{2}_{3}/{4}".format(
instance.guardian.last_name,
instance.guardian.first_name,
instance.patient.last_name,
instance.patient.first_name,
filename,
)
class Claim(models.Model):
patient = models.ForeignKey("Patient", on_delete=models.CASCADE)
guardian = models.ForeignKey("Guardian", on_delete=models.CASCADE)
start_date = models.DateField("Start Date")
end_date = models.DateField("End Date")
creation_date = models.DateField("Creation Date", default=datetime.now)
sum = models.IntegerField("Claim Sum")
pdf = models.FileField("Claim File", upload_to=claim_path)
These are the important sections of settings.py:
INSTALLED_APPS = [
...
"django_sendfile",
...
]
# media
MEDIA_URL = "/protected/"
MEDIA_ROOT = "/protected/"
# for django_sendfile2
SENDFILE_BACKEND = "django_sendfile.backends.nginx"
SENDFILE_ROOT = "/protected/"
SENDFILE_URL = "/protected/"
this is the view that should serve the pdf (don’t mind the name, later on I want to embed this on the website as a preview):
def show_pdf_preview(request, claim_id):
if request.user.is_authenticated:
claim = Claim.objects.get(id=claim_id)
if claim.guardian == request.user.guardian:
logging.info(f"trying to show pdf preview using filename '{claim.pdf.path}'")
return sendfile(request, claim.pdf.path)
else:
return HttpResponseForbidden
else:
return HttpResponseForbidden
Here is my nginx default.conf:
upstream django {
server django_gunicorn:8000;
}
server {
listen 80;
location / {
proxy_pass http://django;
}
location /static/ {
alias /static/;
}
location /protected/ {
internal;
root /protected/;
}
}
And finally, this is the error message I get on the docker stdout:
nginx | 2024/06/06 13:08:16 [error] 29#29: *1 open() "/protected/protected/archive/Admin_Admin/Test_Test/2024-06-06_142405.862381.pdf" failed (2: No such file or directory), client: 172.18.0.1, server: , request: "GET /show_pdf_preview/65/ HTTP/1.1", upstream: "http://172.18.0.3:8000/show_pdf_preview/65/", host: "localhost:8080", referrer: "http://localhost:8080/show_claims/"
nginx | 172.18.0.1 - - [06/Jun/2024:13:08:16 +0000] "GET /show_pdf_preview/65/ HTTP/1.1" 404 153 "http://localhost:8080/show_claims/" "Mozilla/5.0 (X11; Linux x86_64; rv:126.0) Gecko/20100101 Firefox/126.0" "-"
And yes, the file IS there. I checked it. Several times. I also already checked the file permissions and set them to rwxrwxrwx for testing. I have also been trying around with the backslashes because the django_sendfile2 documentation mentioned faulty paths. All with no success. Can anybody point my to my mistake?
Greetings
André