Admin FileField current url incorrect
Asked Answered
M

2

7

In the Django admin, wherever I have a FileField, there is a "currently" box on the edit page, with a hyperlink to the current file. However, this link is appended to the current page url, and therefore results in a 404 as there is no such page as, for example: http://127.0.0.1:8000/admin/Tank/asset/17/media/datasheet/13/09/05/copyright.html/
For reference, the correct url of the file is: http://127.0.0.1:8000/media/datasheet/13/09/05/copyright.html

Is there any way to fix this problem in the default admin layout? It affects every FileField in my database, and seems to me like a bug. Am I just using it wrong?

Mizell answered 5/9, 2013 at 9:26 Comment(0)
T
9

settings.py

add the lines:

import os
BASE_DIR = os.path.realpath(os.path.dirname(__file__))

replace the lines:

MEDIA_ROOT = ''
MEDIA_URL = ''

with

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

this should setup your project to render your media content from the folder /your project directory/media/

urls.py

also add the line:

import settings

add the following line in your url patterns:

url(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT, 'show_indexes': False}),

models.py

inside your model add the following line:

File = models.FileField('File',upload_to='./')

define the method in the model

def fileLink(self):
    if self.File:
        return '<a href="' + str(self.File.url) + '">' + 'NameOfFileGoesHere' + '</a>'
    else:
        return '<a href="''"></a>'
fileLink.allow_tags = True
fileLink.short_description = "File Link"

admin.py

use the field fileLink as a read only field, you can also add it to your list_display

eg

class FileAdmin(admin.ModelAdmin):
    list_display = ['fileLink']
    readonly_fields = ['fileLink']
Truncated answered 9/12, 2013 at 15:15 Comment(1)
it's been a while but, do you have any idea why instead of the link I would get the HTML a element as a string getting displayed in the forms rather than the actual link? (in Django 2.x)Alevin
R
0

The answer to this question is fairly thoroughly covered by this answer. In brief however, the problem is that you probably haven't set up your MEDIA_ROOT and MEDIA in settings.py and in urls.py you haven't made it so that the media folder is being served.

For the details of how to do those things check out the incredibly awesome answer by Akseli Palen.

Raab answered 8/12, 2013 at 7:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.