SBrain
SBrain

Reputation: 313

How to download file from django admin

I created FileField in class Part in models.py. Also I get the link of this file by method file_link(self):

origin = models.FileField(upload_to='origin_files', null=True, blank=True)

    def file_link(self):
        try:
                return "<a href='%s'>download</a>" % (self.origin.url,)
        except PageNotAnInteger:
            return "<a href=127.0.0.1:8000/main>download</a>"

    file_link.allow_tags = True

In admin.py I added readonly_fields for file_link. Also I added in fieldsets file_link:

readonly_fields = ('file_link',)

fieldsets = (
    ('Характеристики плёнки', {
        'fields': (....'data', 'origin', 'file_link')
    }),

)

So, in my django admin I have FileField which allows to upload files to directory origin_files and link to this file. But when I click on this link I'm redirecting to home page of my site. For example, I downloaded file presentation.pptx. When I get url of this file I get

http://127.0.0.1:8000/admin/description/part/12/change/origin_files/Presentation.pptx

How I can download this file?

Upvotes: 0

Views: 2996

Answers (1)

Bob
Bob

Reputation: 6173

You have to configure MEDIA_URL in your django settings

https://docs.djangoproject.com/en/2.0/ref/settings/#media-url

Django builds your url the following way:

settings.MEDIA_URL + "origin_files/Presentation.pptx"

the MEDIA_URL default is an empty string, therefore you get the url "origin_files/Presentation.pptx" and your browser concatenates it to the current page, because the url doesn't start with a slash.

so you have to set the MEDIA_URL for example to '/media/'

then everything will work in your development environment.

On remote server this also requires configuring the web server appropriatelly for it to serve your MEDIA_ROOT to MEDIA_URL (out of the scope of this question obviously).

Upvotes: 1

Related Questions