how django access files to use them?

Hi!

I’m trying to reproduce a basic audio from the basic media folder

In the template I have:

<button onclick="playAudio()">test audio!</button>

In the .js I have:

function playAudio() {
  audio = new Audio('media/test_audio.mp3');
  audio.Play();
}

Then I press the button and get in the console that the http://localhost:8000/beats/media/test_audio.mp3 does not exist, so gives a 404

Any idea how i can solve this?, is there any part in django that tells how it access the files in the file system?

See the Django docs for Managing files. You have a decision to make - are these files that are all going to be predetermined on the server, or are they going to be user-uploadable?

If the former, they would be handled just like any of your other static files (css, js, images, etc). If the latter, then you want to read up on MEDIA_ROOT and MEDIA_URL for supporting user-uploaded files.

I already read the things you said, I readed it again just in case, I can’t make it work

I have this in the settings.py:

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

I imported this into the urls.py:

from django.conf import settings
from django.conf.urls.static import static

Added this into urlspatterns:

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

And that’s it, I don’t know what else to do

First thing is, you don’t want MEDIA_ROOT to be within your project directory. It should be a completely separate directory since people are going to be uploading files to it.

You’ll want to check your view that is allowing people to upload the files, and then the view and template that creates the page that displays the file names and links to play them.

Feel free to post them here if you want further help.

Note: When posting code here, enclose it between lines consisting of three backtick - ` characters. This means you’ll have a line of ```, then your code, then another line of ```. This allows the forum software to keep your code properly formatted.

Trying to explain it to you made me come across the mistake, I was rendering the path of the file in the template instead of the url

I was doing:

{{each_song.sonf_file.path}}

But I needed:

{{each_song.sonf_file.url}}

I’m really new, so this is going to be used only for myself, that’s why MEDIA_ROOT is inside the project folder, I hope that makes it okay for now?

And thanks for telling me how to do the code blocks

Thanks thanks thanks

I guess it’s ok - it’s your system and if anything goes wrong, you’re the only one affected.

But I’d still suggest that you store the media elsewhere. If nothing else, you could directly copy your library into that directory and then write a script to add all the files to the database without having to manually add each one.