Admin FileField current url incorrect

后端 未结 2 1102
孤城傲影
孤城傲影 2021-02-09 08:15

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 curr

2条回答
  •  孤城傲影
    2021-02-09 08:16

    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.*)$', '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 '' + 'NameOfFileGoesHere' + ''
        else:
            return ''
    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']
    

提交回复
热议问题