Django itself doesn’t serve media files in production. You need to use a separate web server instance or a cloud storage service as a media server. This is as much about performance as it is about security. According to Django’s official documentation, it strongly advises against it because it is inefficient and potentially insecure. However, Django can help you during development with the django.views.static.serve() view.
Here is an example of a common setup using Nginx as a media server. Nginx is a popular web server choice for this task given its proven performance and configuration flexibility.
You need to set your MEDIA_URL and MEDIA_ROOT in your settings.py file:
```
Next, you configure Nginx to serve files from that directory. In your Nginx configuration file, you might have something like:
```
server {
…
Remember to collect all app’s static files into the STATIC\_ROOT using the Django’s collectstatic command:
```
python manage.py collectstatic
```
This setup implies that Nginx will handle requests for static files and pass other requests onto Django.
Regarding cloud storage services, AWS S3 is popular. Django Storages is a collection of custom storage backends with Django. To use Django Storages with AWS S3, first install it:
```
pip install django-storages[boto3]
```
Then add it to your installed apps and set your STATICFILES_STORAGE and DEFAULT_FILE\_STORAGE:
```
INSTALLED_APPS = [
…
‘storages’,
]
AWS_ACCESS_KEY_ID = ‘your AWS access key id‘
AWS_SECRET_ACCESS_KEY = ‘your AWS secret access key‘
AWS_STORAGE_BUCKET_NAME = ‘your AWS storage bucket name‘
AWS_S3_CUSTOM_DOMAIN = f’{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com‘
AWS_LOCATION = ‘static’
STATIC_URL = f’https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/‘
STATICFILES_STORAGE = ‘storages.backends.s3boto3.S3Boto3Storage‘
DEFAULT_FILE_STORAGE = ‘storages.backends.s3boto3.S3Boto3Storage‘
```
Remember to replace ‘AWS_ACCESS_KEY_ID’ and ‘AWS_SECRET_ACCESS_KEY’ with your actual AWS Access Key and Secret Key.
Look out for any CORS issues as these are common when browser security policies prevent resources from different domains. This can be solved by setting appropriate CORS policy on your server.
Sources:
1. Django official documentation: https://docs.djangoproject.com/en/3.1/howto/static-files/#serving-static-files-during-development
2. Nginx documentation: http://nginx.org/en/docs/beginners\_guide.html#proxy
3. Django Storages documentation: https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html
4. AWS S3 documentation: https://aws.amazon.com/premiumsupport/knowledge-center/s3-configure-correct-bucket-policy/