Now lets say we want our backend to be able to render images in the browser. First we need a place to store these images. Create a new folder called ‘media’ in the root of your project and upload an image ‘dog.jpg’ into it.
The next thing we do is to go into our settings.py file, and right under where we have specified our static url, we need to set our media url there. Now note that static url is the url pointing to the directory where we will host stuff like html, css and javascript stuff. Same thing for our media url. so we do something like this
import os
MEDIA_URL = '/media/'MEDIA_ROOT = os.path.join(BASE_DIR, 'media')The media root is simply the path from our root directory all the way to the media folder. We use the os module and the path.join method to do that.
Next we go to our urls.py file, and we want to add a url to link us to our media. Now we only want to do this while our app is in development mode(i.e DEBUG is turned on.) so we append out media url only if we’re in dev mode. see below
from django.conf import settingsfrom django.conf.urls.static import static
urlpatterns = [ path('admin/', admin.site.urls), path('playground/', include('playground.urls')), path('store/', include('store.urls')), path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.jwt')), path('__debug__/', include(debug_toolbar.urls)),]
if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)Now in our browser when we go to ‘127.0.0.0:8000/media/dog.jpg’ we will see our image in the browser