django无法删除音频文件,因为它被音频播放器使用

时间:2018-08-01 19:53:00

标签: python django audio

我创建了一个django网站,用户可以在其中上传音乐文件并使用HTML5音频播放器播放音乐文件

那是我的模特

from django.db import models
from django.db.models.signals import post_delete
from django.dispatch import receiver

# Create your models here.


class User(models.Model):


    id=models.AutoField(primary_key=True)
    email=models.CharField(max_length=30,unique=True,null=False,blank=False)
    password=models.CharField(max_length=30,unique=True,null=False,blank=False)
    name=models.CharField(unique=True,max_length=40,null=False,blank=False)

    def __str__(self):
        return self.name.title()+","+self.email


class Song(models.Model):

    id=models.AutoField(primary_key=True)
    title=models.CharField(max_length=100,null=False,blank=False)
    artist=models.CharField(max_length=100,null=False,blank=False)
    user=models.ForeignKey(User,null=False,blank=False)
    file = models.FileField(null=False,blank=False)


    def __str__(self):
        return self.artist+" - "+self.title


# I can't delete the song file because it's used by the audio player in html
@receiver(post_delete, sender=Song)
def submission_delete(sender, instance, **kwargs):
    instance.file.delete(False)

这是用于显示歌曲的html代码

{% for song in songs %}
    <div class="card">
        <div class="card-body">
            <h5 class="card-title">{{song.artist}} - {{song.title}}</h5>
            <audio controls>
                <source src="/media/{{song.file}}" type="audio/ogg" />
            </audio>
        <a href="/delete/{{song.id}}" onclick="confirm_delete_song('/delete/{{song.id}}')" class="delete" > <i class="material-icons" title="Supprimer">&#xE872;</i></a>
        </div>
    </div>
{% endfor %}

以及删除歌曲的视图

def delete(request, song):
    if 'logged' not in request.session:
        return HttpResponseRedirect('/')
    else:
        try:
            Song.objects.get(id=song).delete()
            return HttpResponseRedirect('/')
        except:
            return HttpResponseRedirect('/')

页面截图

enter image description here

当我单击“删除”按钮时,歌曲将从数据库中删除,但是即使我尚未播放音频,文件也不会被删除

经过调试后,似乎音频播放器正在使用音频文件,这就是django无法删除它的原因

[WinError 32]该进程无法访问文件,因为该文件正被另一个进程使用:'C:\ Users \ Amine \ Desktop \ omp \ media \ remix.mp3'

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:0)

尝试一下,

def delete(request, song):
    if 'logged' not in request.session:
        return HttpResponseRedirect('/')
    else:
        try:
            song = Song.objects.get(id=song)
            song.file.delete()  # File delete
            song.delete # object delete
            return HttpResponseRedirect('/')
        except:
            return HttpResponseRedirect('/')

答案 1 :(得分:0)

在删除之前,我终于可以通过使用javascript将音频标签的src属性设置为空字符串来解决此问题。这导致文件免费