Search code examples
pythondjangovs-web-site-project

django play/download mp3 file


i am making a website with a list of mp3 files and i want a detail view. the problem is django cannot find the mp3 file. it shows up in the source code and the audio bar shows up so i can play/pause adjust volume etc in download.html i use {{ object.file.url }} in a h1 tag, the url is correct but django gives me a 404 error in the console. i want the url to be http://example.com/download/(id) then the download.html shows and they can play the mp3 file or download it.

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


Solution

  • SOLVED

    setting.py this saves the uploaded files to the static folder

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

    download.html put /static in the begin to go to /static then file path.

    <!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>