django play/download mp3 文件

django play/download mp3 file

我正在制作一个包含 mp3 文件列表的网站,我想要一个详细视图。 问题是 django 找不到 mp3 文件。 它显示在源代码中,并且显示音频条,因此我可以 play/pause 调整音量等 在 download.html 中,我在 h1 标签中使用 {{ object.file.url }},url 是正确的,但 Django 在控制台中给我一个 404 错误。 我希望 url 成为 http://example.com/download/(id) 然后 download.html 显示,他们可以播放 mp3 文件或下载它。

download.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Download</title>
</head>
<body>
<audio controls>
    <source src="{{ object.file.url }}" type="audio/mpeg">
    Your browser does not support audio
</audio>
<h1>{{ object.file.url }}</h1>
</body>
</html>

views.py

from django.shortcuts import render, get_object_or_404, reverse
from .models import Song


def index_view(request):
    queryset = Song.objects.all()
    context = {
        'list': queryset
    }

    return render(request, 'index.html', context)


def download_view(request, id):
    obj = get_object_or_404(Song, id=id)

    context = {
        'object': obj,
    }

    return render(request, 'download.html', context)

setting.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'pages',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'music.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'music.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = ''
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]

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

urls.py

from django.contrib import admin
from django.urls import path
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

from pages.views import index_view, download_view

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index_view),
    path('download/<int:id>', download_view)
]
urlpatterns += staticfiles_urlpatterns()

models.py

from django.db import models


class Song(models.Model):
    title = models.CharField(max_length=122, blank=True, null=True, default="No Title")
    by = models.CharField(max_length=122, blank=True, null=True)
    file = models.FileField(upload_to="media")

    def __str__(self):
        return self.title

已解决

setting.py 这会将上传的文件保存到静态文件夹

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

download.html 把 /static 放在开始去 /static 然后文件路径。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Download</title>
</head>
<body>
<audio controls>
    <source src="/static{{ object.file.url }}" type="audio/mpeg">
    Your browser does not support audio
</audio>
<h1>{{ object.file.url }}</h1>
</body>
</html>

您还可以对 url 进行硬编码以查找特定的音频文件,然后获取下载 url 进行下载,但 每次 都会创建任何使用静态文件的 django 项目确保首先指定静态文件夹或仅使用 django 模板和 static 文件管理约定。