Uploading Images in Django
When defining the models we used the ImageField for uploading images and we wrote the upload_to parameter as upload_to=”images/%Y/%m/%d”) because this will create a directory data structure of the format image>>year>>month>>date so that tracking images may become easier.
Before uploading the image we need to write the below code in the setting.py file.
Python3
MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = '/media/' |
- MEDIA_ROOT is for server path to store files in the computer.
- MEDIA_URL is the reference URL for browser to access the files over Http
In the urls.py we should edit the configuration like this
from django.conf import settings from django.conf.urls.static import static if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Let’s see how to upload data into the model using Django Admin Interface.
Python Web Development With Django
Python Django is a web framework that allows to quickly create efficient web pages. Django is also called batteries included framework because it provides built-in features such as Django Admin Interface, default database – SQLite3, etc. When you’re building a website, you always need a similar set of components: a way to handle user authentication (signing up, signing in, signing out), a management panel for your website, forms, a way to upload files, etc. Django gives you ready-made components to use.