0
votes

I have a cloned project and I need to serve the static files with Django itself. It is my first time serving static files this way (in the past I used Nginx/Apache to serving media and static files). here is my try to serve static files by Django itself in production:

1- Adding STATIC_URL and STATIC_ROOT to settings.py:

...
STATIC_URL = '/static/'
STATIC_ROOT = os.environ.get('DH_STATIC_ROOT_DIR', os.path.join(BASE_DIR, 'static/'))

2- project's directory tree:

├── my_project
│   ├── DH
│   ├── env
│   ├── apps
│   ├── manage.py
│   ├── README.md
│   ├── requirements.txt
│   ├── static
│   └── templates

3- running ./manage.py collectstatic and working well. here is static/ directory's tree after this command (from past some static file exists in static directory because this project is MVT and loading templates):

├── admin
├── css
├── fonts
├── js
├── media
└── plugins

4- let Django serve static in production( in urls.py):

from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
    path('', index, name='index'),
    path('admin/', admin.site.urls)
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

5- how html templates reference to static files:

{% load static %}
...
<link href="{% static 'plugins/global/plugins.bundle.css' %}" rel="stylesheet" type="text/css" />

For example, in Chrome (inspect) I can see the template page request to http://127.0.0.1:8000/static/media/logos/logo-6.png that static/media/logos/logo-6.png exist (all request to static files raise 404 HTTP status code). with this configuration not working even in DEBUG=True what I am doing wrong? Thank you in advance.

1

1 Answers

1
votes

As documentation states, serve not suppose to be used in production. If you don't want to use nginx or apache, then consider using whitenoise. All you need to do is install it by pip install whitenoise and add these lines to middleware:

MIDDLEWARE = [
  'django.middleware.security.SecurityMiddleware',
  'whitenoise.middleware.WhiteNoiseMiddleware',
  # ...
]