Invalid FileField Admin URL

In the Django admin, wherever I have FileField, the edit page has a โ€œcurrentโ€ window with a hyperlink to the current file. However, this link is added to the current URL of the page and, therefore, leads to 404, since there is no such page, such as: http://127.0.0.1:8000/admin/Tank/asset/17/media/datasheet/13/09/05/copyright.html/
For reference, the correct file URL is: http://127.0.0.1:8000/media/datasheet/13/09/05/copyright.html

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

+4
source share
2 answers

settings.py

add lines:

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

replace strings:

 MEDIA_ROOT = '' MEDIA_URL = '' 

from

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

this should set up your project to display media content from the folder / of your project directory / media /

urls.py

also add the line:

 import settings 

add the following line to 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 a method in a 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 fileLink field as a read field, you can also add it to your list_display

eg,

 class FileAdmin(admin.ModelAdmin): list_display = ['fileLink'] readonly_fields = ['fileLink'] 
+4
source

The answer to this question is covered in some detail by this answer . In short, however, the problem is that you probably did not configure your MEDIA_ROOT and MEDIA in settings.py and in urls.py you did not do this so that the media folder is loaded.

For more on how to do these things, see Axeli Palen โ€™s incredibly amazing answer.

0
source

Source: https://habr.com/ru/post/1500686/


All Articles