0

I have a model that takes a File Field which is uploaded in Django admin. I noticed that the files save in the proper folder. But when Debug is set to False, I cannot access the file from the admin area or from the front end user interface. I get an error message that says "The resource could not be found on the server."

The app is hosted on Heroku and does the same thing in localhost and live. I read in another post that Whitenoise would work with Heroku but it hasn't resolved the issue. Could someone please point me in the right direction to a fix? The relevant files are below.

Update: Adding urls.py

urls.py


from django.contrib import admin
from django.urls import include, path
from django.conf.urls.static import static
from django.conf import settings
from .views import DatasetListView
from django.conf import settings
import pages.views

urlpatterns = [
    path('', include('pages.urls')),
    path('users/', include('users.urls')),
    path('accounts/', include('allauth.urls')),
    path('admin/', admin.site.urls),
    path('downloads/', views.DatasetListView.as_view(), name='downloads'), # where users download the files
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

models.py

from django.core.files.storage import FileSystemStorage
from django.db import models

class DataSet(models.Model):
    title = models.CharField(max_length=255)
    date_added = models.DateField(auto_now=True)
    file_size = models.CharField(max_length=20)
    file_type = models.CharField(max_length=20)
    data_file = models.FileField(upload_to='delivery/')

    def __str__(self):
        return self.title

settings.py

import os
import django_heroku
import dj_database_url

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


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

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

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'whitenoise.runserver_nostatic',
    'django.contrib.staticfiles',
    'django.contrib.sites',

    # third-party apps
    'anymail',

    # project apps
    'pages',
    'users',
    'allauth', 
    'allauth.account', 
    'allauth.socialaccount', 
]

AUTH_USER_MODEL = Redacted

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'myapp.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, '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',
                'django.template.context_processors.media',
            ],
        },
    },
]

WSGI_APPLICATION = 'myapp.wsgi.application'


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


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

# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'


AUTHENTICATION_BACKENDS = (
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend",
)

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
            'datefmt' : "%d/%b/%Y %H:%M:%S"
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'mysite.log',
            'formatter': 'verbose'
        },
    },
    'loggers': {
        'django': {
            'handlers':['file'],
            'propagate': True,
            'level':'DEBUG',
        },
        'MYAPP': {
            'handlers': ['file'],
            'level': 'DEBUG',
        },
    }
}

# Configure Django App for Heroku.
django_heroku.settings(locals())

Thanks for your help.

Erin B.
  • 165
  • 3
  • 15
  • Can you also please add `urls.py`, so that we can see those actual URL resolvings to understand the situation better – Bedilbek Nov 23 '19 at 12:56
  • Sure, I've just updated the question with the urls.py code – Erin B. Nov 23 '19 at 13:11
  • Actually, `urls.py` showed the problem. So, django does not provide file serving on production and it is a problem when you deploy to PaaS like Heroku. Why it is working on `debug=True`, because with that settings it provides kind of static file serving for the only purpose of development. I really recommend you to read WhiteNoise for serving static files from other cloud servers. – Bedilbek Nov 23 '19 at 13:35
  • Ok thanks I thought Whitenoise was enough. I'll look at a CDN. – Erin B. Nov 25 '19 at 15:03

0 Answers0