I have model with FileField, which contains audio file:
class Word(models.Model):
theme = models.ManyToManyField(Theme, related_name='words')
name = models.CharField(max_length=200, null=True, blank=True)
sound = models.FileField(upload_to='sounds/', blank=True)
I need show audio player on admin panel for this model.
For example, for ImageField I did this:
from django.utils.html import mark_safeand add property to model code
@property
def icon_preview(self):
if self.icon:
return mark_safe(f'<img src="{self.icon.url}" width="100" height="100" />')
return ""
- in
admin.pyadd code:
list_display = ('id', 'name', 'icon', 'icon_preview')
readonly_fields = ('icon_preview',)
def icon_preview(self, item):
return item.icon_preview
icon_preview.short_description = 'icon preview'
icon_preview.allow_tags = True
And I need to do something similar for the sound
CodePudding user response:
Perhaps you could link to the audio file, similar to what you did for the image, and let the browser play the file when the user clicks the link.
For example, using format_html:
from django.utils.html import format_html
@admin.display(description='Sound', ordering='sound')
def sound_display(obj):
link = 'not available'
if obj.sound:
link = format_html('<a href="{}">sound</a>', obj.sound.url)
return link
and then use it like this in your list_display:
list_display = (..., sound_display)
You could also use the HTML <audio> tag, as suggested by @AKX.
CodePudding user response:
It seems to be working:
- Add to model
Wordthis property:
@property
def sound_display(self):
if self.sound:
return mark_safe(f'<audio controls name="media"><source src="{self.sound.url}" type="audio/mpeg"></audio>')
return ""
- In
admin.pyadd this construction:
list_display = ('id', 'name', 'transcription', 'translation', 'example', 'sound_display')
readonly_fields = ('sound_display',)
list_display_links = ('id', 'name')
def sound_display(self, item):
return item.sound_display
sound_display.short_description = 'sound'
sound_display.allow_tags = True
