Search code examples
djangodjango-staticfiles

Using django-environ; Django admin css not found


I removed the BASE_DIR and the os import because I am using django-environ.

However when I entered the admin dashboard of Django, the css is not read so I only see plain html elements.

Here is how part of my settings.py looks like.

import environ


root = environ.Path(__file__) - 3  # get root of the project
env = environ.Env()
environ.Env.read_env()  # reading .env file

SITE_ROOT = root()

DEBUG = env.bool('DEBUG', default=False)
TEMPLATE_DEBUG = DEBUG

ALLOWED_HOSTS = tuple(env.str('ALLOWED_HOSTS', default=[]))
DATABASES = {
    'default': env.db('DATABASE_URL')
}


SECRET_KEY = env.str('SECRET_KEY')


# Static and Media Config

public_root = root.path('public/')
MEDIA_ROOT = public_root('media')
# MEDIA_ROOT = root.path('media/')
MEDIA_URL = env.str('MEDIA_URL', default='media/')
STATIC_ROOT = public_root('static')
STATIC_URL = env.str('STATIC_URL', default='static/')

ROOT_URLCONF = 'myproject.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [root.path('templates/'), ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

So I also put in root.path('templates') into the DIRS of TEMPLATES.

I also added this snippet below to the project's urls.py.

if settings.DEBUG:
    urlpatterns += static(
        settings.MEDIA_URL,
        document_root=settings.MEDIA_ROOT
    )

I also have this on my .env file:

DEBUG=True
ALLOWED_HOSTS=localhost,127.0.0.1
MEDIA_URL=media/
STATIC_URL=static/

Where could I have gone wrong and what should be written instead?


Solution

  • I looked into djangogirls tutorial and found out that I missed out some slashes.

    From my .env file:

    MEDIA_URL=media/
    STATIC_URL=static/
    

    I changed it into

    MEDIA_URL=/media/
    STATIC_URL=/static/