简体   繁体   English

将声音播放器添加到 django 管理面板

[英]Add sound player to django admin panel

I have model with FileField , which contains audio file:我有FileField模型,其中包含音频文件:

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:例如,对于ImageField我这样做:

  1. from django.utils.html import mark_safe and add property to model code from django.utils.html import mark_safe并将属性添加到模型代码
@property
def icon_preview(self):
    if self.icon:
        return mark_safe(f'<img src="{self.icon.url}" width="100" height="100" />')
    return ""
  1. in admin.py add code:admin.py添加代码:
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我需要为声音做类似的事情

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 :例如,使用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中像这样使用它:

list_display = (..., sound_display)

You could also use the HTML<audio> tag, as suggested by @AKX .您还可以使用 HTML<audio>标签, 正如 @AKX 所建议的那样

It seems to be working:它似乎正在工作:

  1. Add to model Word this property:将此属性添加到模型Word
@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 ""
  1. In admin.py add this construction:admin.py添加这个结构:
   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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM