Unlike static files, media files are the files (images , pdf or any other documents etc) uploaded by user.
Media root is the directory where media files are stored
URL that handles the media served from MEDIA_ROOT, used for managing stored files. It must end in a slash if set to a non-empty value.
Add following lines at the end of settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/'
├── static │ ├── css │ ├── img │ └── js ├── templates │ ├── components │ └── blog ├── media
we need to configure main urls.py file as below
from django.contrib import admin from django.urls import path, include from . import settings #add this for media from django.contrib.staticfiles.urls import static #add this for media from django.contrib.staticfiles.urls import staticfiles_urlpatterns #add this for media urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls')),# Add this line for new app ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #add this for media
You also need to define a field which will accept media file.
class Post(models.Model): . . . featured_image = models.ImageField(upload_to='img', blank=True, null=True) . .
Please note the “upload_to” option. Here, “img” folder will get created (you dont have to create it manually) and files will be stored and served from here.
Once these changes are done , don’t forget to run following commands
$ python3.6 manage.py makemigrations blog $ python3.6 manage.py migrate
Now start the server using following command and start using media files.
python3.6 manage.py runserver
If you run into any issue, please let me know