Search code examples
pythondjangoformsfile-uploadfilefield

Access to file uploaded with FileField Django


I'm trying to create a Django form with a filefield to upload a pdf based on a model.

#models.py
class ProductionRequest(models.Model):
     ...
     contract_file = models.FileField('Contract file (PDF)', upload_to='contracts/')
     ...

I can upload the file and save it in my object, but when I try to show the file in my template with this code

 {{ prod_req.contract_file }}

it only show me the path to the file "contracts/file_uploaded.pdf". How can I make a link to download (or open in a new tab ) the file ?

Plus : when I try to open the file from Django admin, with this link

Contract file (PDF) : Currently: contracts/file_uploaded.pdf

I don't show me the file, i got this :

Page not found (404) Request URL: http://127.0.0.1:8000/admin/appname/productionrequest/1/change/contracts/file_uploaded.pdf/change/

How can I access to my file ?


Solution

  • It works just like a Python file. So, the way you have just refers to a file object.

    To get the text, you need to use f.read(). So, in your template, instead of

    {{ prod_req.contract_file }}
    

    use

    {{ prod_req.contract_file.read }}
    

    BUT, note that calling read moves the cursor to the end of the file. The first time you call read on a file, it returns all the text. The second time, it returns nothing. This is only a problem if you need the text twice, but in that case, store the text directly on the context object.

    Let me know if anything was unclear.