2👍
✅
You can use formfield_overrides to modify the AdminFileWidget. This AdminFileWidget can display images and mp4 files, but you can use only for images omitting the if file_name[-4:] == '.mp4':
part.
from django.db.models.fields.files import FileField
from django.contrib.admin.widgets import AdminFileWidget
class AdminMediaWidget(AdminFileWidget):
def render(self, name, value, attrs=None):
output = []
if value and getattr(value, "url", None):
image_url = value.url
file_name = str(value)
if file_name[-4:] == '.mp4':
output.append('<video width="320" height="240" controls>'
'<source src="{0}" type="video/mp4">'
'Your browser does not support the video tag.'
'</video>'.format(image_url))
else:
output.append('<a href="{0}" target="_blank">'
'<img height=200 src="{1}" alt="{2}" />'
'</a>'.format(image_url, image_url, file_name))
output.append(super(AdminFileWidget, self).render(name, value, attrs))
return mark_safe(''.join(output))
class UserAdmin(admin.ModelAdmin):
formfield_overrides = {
FileField: {'widget': AdminMediaWidget},
}
exclude = ('user_avatar',)
readonly_fields = ('avatar_readonly',)
def avatar_readonly(self, instance):
value_link = "/mediafileupdown/download/" + str(instance.id)
value_desc = str(instance.user_avatar.name)
return format_html('<a href="{}">{}</a>', value_link, value_desc)
avatar_readonly.short_description = "User avatar (read only)"
avatar_readonly.allow_tags=True
Hope it helps!
Source:stackexchange.com