Home > Software design >  Django downloading a file
Django downloading a file

Time:12-19

i have a db i made it with Django, and with the models.CharField I created the path how the users going to upload a file in their post. in MEDIA_URL = "/media/" but i tried to let the user download the content (the file) throw a link or just a click. how can i do that! i have a multiple files name in my models.py like this:

files_Tensile = models.FileField(blank=True, null=True, upload_to="chapters/%Y/%m/%D")
files_Charpy = models.FileField(blank=True, null=True, upload_to="chapters/%Y/%m/%D")
files_Modulus = models.FileField(blank=True, null=True, upload_to="chapters/%Y/%m/%D")
Diagramm_Hohen_Temp = models.ImageField(blank=True, null=True, upload_to="chapters/%Y/%m/%D")
files_Metallo = models.FileField(blank=True, null=True, upload_to="chapters/%Y/%m/%D")
Gefüge = models.ImageField(blank=True, null=True, upload_to="chapters/%Y/%m/%D")
Diagramm_Wärmebehandlung=models.ImageField(blank=True,null=True,upload_to="chapters/%Y/%m/%D")
files_Density = models.FileField(blank=True, null=True, upload_to="chapters/%Y/%m/%D"

the views.py:

    def download(request, path):
        file_path = os.path.join(settings.MEDIA_ROOT, path)
        if os.path.exists(file_path):
            with open(file_path, 'rb') as fh:
                response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel")
                response['Content-Disposition'] = 'inline; filename='   os.path.basename(file_path)
                return 

response
    raise Http404

in the html:

<td><a  href="media/files_Density/download"> Download Files</a></td>

I get the error, Page not found (404). can anyone please explain how to fix this?

CodePudding user response:

the MEDIA_URL = "/media/" is for a user to view user created files after uploaded

the easiest way to download a file on click (that is on the same server as the webpage) is to add in the html a tag a download attribute

in the html

<td><a  href="fileURLGoesHere" download> Download Files</a></td>

CodePudding user response:

I think you should replace the CharField with a FileField as this will handle a lot of this on your behalf :) including saving it to the media/ directory, or, you can specify somewhere else, just need to read the docs

  • Related