Luca
Luca

Reputation: 10996

downloadable file link in django tables

I am using django-tables2 and have a view which basically should allow user access to the data store. My table model has a link column is as follows:

class DummyTable(tables.Table):
    download = tables.LinkColumn('dummy_download', args=[tables.A('pk')], orderable=False,
                                 empty_values=(), verbose_name='')

The rendering of the link column is done as follows:

    class Meta:
        model = DummyModel
        attrs = {'class': 'paleblue'}   


    def render_download(self):        
        url = static('cloud-download.png')
        media_root = settings.MEDIA_ROOT
        href = media_root + "/mask.nii.gz"        
        return mark_safe('<a href="' + href + '"><img src="' + url + '"></a>')

So basically I have some data in my /media folder which I would like to allow the user to download when the link is clicked. However, I am unable to generate the correct link in the render_download method. Putting the link simply as I have it does not initiate any download even though it seems to point to the correct file location (locally). Also, I am not sure if this will work when someone connects remotely. I have a feeling it should call some reST API internally to initiate the download but I am not sure how to achieve this.

The settings.py file configures the media settings as follows:

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/' 

I tried using the MEDIA_URL as the link but then it tries to match it with url configurations and returns with:

Using the URLconf defined in cloud.urls, Django tried these URL patterns, in this order:

^admin/
^$ [name='index']
^login/$ [name='login']
^logout/$ [name='logout']
^images/$ [name='images']
^static\/(?P<path>.*)$
The current URL, media/mask.nii.gz, didn't match any of these.

Upvotes: 0

Views: 1060

Answers (1)

flowfree
flowfree

Reputation: 16462

I think you should get the value of MEDIA_URL instead of MEDIA_ROOT:

def render_download(self):        
    url = static('cloud-download.png')
    href = settings.MEDIA_URL + "/mask.nii.gz"        
    return mark_safe('<a href="' + href + '"><img src="' + url + '"></a>')

You might need to add the following to your main urls.py so your media files can be served by the development web server.

# urls.py

...
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns = [
    # ...your routes...
] 

urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Upvotes: 1

Related Questions