1

I have created my first Django project, but in the admin panel, when I run http://127.0.0.1:8000/admin/ the CSS files is not loaded and I also created a new Django app but still got the same error, I have also visited the question but my problem is not solved: Django admin site not showing CSS style

It looks like this:

Django Admin Login

I can log in:

Django Admin Dashboard

It should look like this:

Django Admin Login with CSS Django Admin Dashboard with CSS

settings.py

import os

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

urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('products/', include('products.urls'))
]

Note: I have used STATIC_ROOT = os.path.join(BASE_DIR, 'static') in settings.py and also run the command python manage.py collectstatic, but still, I got the same thing.

Hedayatullah Sarwary
  • 2,664
  • 3
  • 24
  • 38

3 Answers3

1

Assuming you have DEBUG=False in settings.py, you need to manually serve static files. Note that this is not recommended for production - you should serve static files using your web server such as apache on nginx. Also note that django will do this automatically, if you have DEBUG=True.

urls.py:

import re

from django.urls import re_path
from django.conf import settings
from django.views.static import serve

urlpatterns = [
    ...
    re_path(r'^%s(?P<path>.*)$' % re.escape(settings.STATIC_URL.lstrip('/')), serve, {"document_root": settings.STATIC_ROOT}),
]

Gasanov
  • 2,839
  • 1
  • 9
  • 21
0

try this might help

from django.conf.urls import url
from django.views.static import serve
from django.conf.urls.static import static
from django.conf import settings


    url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
    url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),
]
if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

or if it still does not work for you set debug=false thane python manage.py collectstatic after creating a static cdn folder and paste you localhost path in allowed host section and then tell us if it still not loading admin css

Shreyash mishra
  • 738
  • 1
  • 7
  • 30
0

Thanks, Guys I added the following in my setting.py file, and now it's working fine:

import mimetypes
mimetypes.add_type("text/css", ".css", True)
Hedayatullah Sarwary
  • 2,664
  • 3
  • 24
  • 38