Django: generate download link

前端 未结 3 1542
梦谈多话
梦谈多话 2020-12-29 08:46

I have a File model, which store path field - path in the filesystem to file. All files are stored in MEDIA_ROOT/files

In template I want g

相关标签:
3条回答
  • 2020-12-29 08:58

    In models.py:

    import os
    
    from django.conf import settings
    from django.db import models
    
    class File(models.Model):
        ... (your existing File model)
    
        @property
        def relative_path(self):
            return os.path.relpath(self.path, settings.MEDIA_ROOT)
    

    (using the relpath method to strip MEDIA_ROOT from the value of self.path)

    In your file_detail.html (or equivalent) template:

    <a href='{{ MEDIA_URL }}{{ file.relative_path }}'>{{ file.name }}</a>
    

    NB as Chris says, it's better to use a FileField here. The above will hopefully work for your exact situation, but unless you're deeply committed to arranging things that way, I'd suggest changing to the dedicated field.

    0 讨论(0)
  • 2020-12-29 09:10

    try using href="{{ STATIC_URL }}/files/somefile", or href="{{ MEDIA_URL }}/files/somefile" for user uploaded content

    0 讨论(0)
  • 2020-12-29 09:17

    I'm not sure what exactly you mean by "generate download link", but to simply link to the file, just use {{ some_file.url }} as your href.

    0 讨论(0)
提交回复
热议问题