Django does not render static files that are in subfolders within /Static/

Asked

Viewed 1,157 times

2

I am working on a Django project that has static files (css/js/imgs) according to the following structure:

File Structure

django_project
    |
    +apps
    |
    +django_project
        |
        +media
        |
        +static
            |
            +admin (múltiplas pastas e subpastas, PROBLEMA)
            |
            +css (apenas arquivos, sem problemas)
            |
            +imgs (apenas arquivos, sem problemas)
            |
            js (apenas arquivos, sem problemas)

When in development, the files work very well, all. However, in production, I am having trouble rendering the files that are inside the admin folder (and its subfolders). When I see the google inspector Chrome, I see that returns an error 404 for these files.

I do not know what is happening, but I imagine it is something related to the urlpatterns.

Follow my files Settings.py and urls.py:

py Settings.

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''

# SECURITY WARNING: don't run with debug turned on in production!
#DEBUG = True
DEBUG = False



ALLOWED_HOSTS = ['*']

MAX_UPLOAD_SIZE = 5242880

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
DEFAULT_FROM_EMAIL = ''

MAIL_SNAKE_API_KEY = ''

LOGIN_REDIRECT_URL = '/app/'

ENDLESS_PAGINATION_PER_PAGE = 8

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'crm',
    'blog',
    'vagas',
    'tinymce',
    'bootstrap3',
    'django_filters',
    'cadastros',
    'projetos',
    'comercial',
    'endless_pagination',
    'easy_pdf',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'django_project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['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',
                'projetos.context_processors.UserInfo',

            ],
        },
    },
]

WSGI_APPLICATION = 'django_project.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': '',
        'USER': '',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '',
    }
}

TINYMCE_DEFAULT_CONFIG = {
    'plugins': "table,paste,searchreplace",
    'theme': "advanced",
    'mode': "textareas",


}

# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'pt-br'

TIME_ZONE = 'America/Fortaleza'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'django_project', 'static'),
)

MEDIA_URL = '/media/'



MEDIA_ROOT = os.path.join(BASE_DIR, 'django_project', "media")

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True

py.

# -*- coding: utf-8 -*-
from django.conf.urls import include, url
from django.contrib import admin
from comercial.views import Proposta, GetPerson, GetPreco, TestePdf
from cadastros.views import EditarProfile
from crm.views import Index, AjaxCotacao, Politica, LeadGen, Pipe, SendEmail, Restrito, PessoasView, CotacoesView
from projetos.views import Jobs, AppDashboard, Arquivo, AddBriefing, Teste, Upload, Timeline, Aprovar
from blog.views import Blog, PostDetail
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth import views as auth_views

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^blog/(?P<pk>\d+)/$', PostDetail, name='PostDetail'),
    url(r'^blog/$', Index),
    url(r'^politica-de-privacidade/$', Politica),
    url(r'^tinymce/', include('tinymce.urls')),
    url(r'^ajax/create_cot/$', AjaxCotacao),
    url(r'^crm/pipe/$', Pipe),
    url(r'^teste/$', SendEmail),
    url(r'^app/$', AppDashboard),
    url(r'^app/teste/$', Teste),

    #cadastros 

    url(r'^app/profile/edit/$', EditarProfile),

    #login
    url(r'^app/login/$', auth_views.login, name='login'),
    url(r'^app/logout/$', auth_views.logout, {'next_page': '/'}, name='logout'),

    #comercial 
    url(r'^app/comercial/$', Proposta),
    url(r'^app/comercial/getperson/$', GetPerson),
    url(r'^app/comercial/getpreco/$', GetPreco),
    url(r'^app/comercial/testepdf/$', TestePdf),

    #pecas
    url(r'^app/pecas/$', Jobs),
    url(r'^app/pecas/(?P<pk>\d+)/$', AddBriefing, name='AddBriefing'),
    url(r'^app/pecas/arquivo/$', Arquivo),
    url(r'^app/pecas/(?P<pk>\d+)/upload/$', Upload, name='Upload'),
    url(r'^app/pecas/(?P<pk>\d+)/timeline/$', Timeline, name='Timeline'),
    url(r'^app/pecas/(?P<pk>\d+)/timeline/aprovar/$', Aprovar, name='Aprovar'),
    url(r'^restrito/$', Restrito),
    url(r'^restrito/pessoas/$', PessoasView),
    url(r'^restrito/comercial/cotacoes/$', CotacoesView),
    url(r'^b1c7879958231cf38ba31c55a46934eef7aa1c502fbffb6c71/$', LeadGen),
    url(r'', Index),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
  • Welcome to Stack Overflow! Welcome to Stackoverflow in English. The official language used here is Portuguese, could you translate your question? If you prefer, you can ask the same question on Stackoverflow.com.

  • Hello ! Sorry, I didn’t realize I was in the stack br :) I already translated..

  • Question reopened!

1 answer

1

Static purchases are only automatically served by Django himself in the development environment.

In the production environment, you must configure your front-end web server to serve the static files automatically, without going through Django and other applications related to the Python environment (such as WSGI servers).

There are several ways to do this - from directly configuring the folder static from your project to be served at a specific URL (which must be the same relative URL that worked in the development environment), to a script to copy the static files to another server, from where they will be served.

Here’s Django’s official documentation on this: https://docs.djangoproject.com/en/1.10/howto/static-files/deployment/

  • Oops! Yes, my webserver is already set up for this ! I will try to be clearer, in the development environment, everything works ok. However, in the production environment, the files only work in the "Static" root folder. I put a folder called "admin" inside this Static folder, and the files inside it are not served.. I was able to be clear ?

  • Yes - but the problem remains the configuration on the external web-server. If you used some script to configure it automatically, try adding sub-folders explicitly in that configuration line: os.path.join(BASE_DIR, 'django_project', 'static'), (put the 'static/admin' there, for example)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.