Reputation: 405
I am trying to handle the django static and media content. This is my code in settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
In urls.py
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I am uploading files and videos to my site, everything is working fine even static and media content is being displayed.
My actual doubt is-
I am actually running in development environment. In production for collecting the static content generally python manage.py collectstatic
is used and then it is handled. But in development according to docs, app called django.contrib.staticfiles
is used serve static files. But what about media files, how are they served actually ??
When I upload a image it is getting stored to project_name/media/app_name
insted of project_name/app_name/media/app_name
as static files are being accessed from path similar to latter, why are media files being stored in different manner.
Finally:
Upvotes: 1
Views: 1396
Reputation: 21779
When I upload a image it is getting stored to
project_name/media/app_name
insted ofproject_name/app_name/media/app_name
as static files are being accessed from path similar to latter, why are media files being stored in different manner.
Media files are uploaded to the MEDIA_ROOT
directory. Your MEDIA_ROOT
is media
, so django will keep uploaded files there.
Additionally, if in the FileField
or ImageField
you use upload_to
path, django will create required folders accordingly. For example, for something like this:
image = models.ImageField(upload_to='myapp/')
Django will create a myapp
folder inside media
and keep the uploaded images there.
- How the media files got served in development ?
Because of this line of code:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
It tells django to serve MEDIA_ROOT
directory at MEDIA_URL
.
- How to serve media files in production ?
Configure your webserver to serve media and static files. Django doesn't serve media and static files because it's not good at that. An actual webserver like Nginx or Apache is configured for serving static files efficiently.
Upvotes: 2