Static files not found - Deploying Django on Heroku - python

I am trying to deploy a Django site on Heroku, but I'm running into problems getting the app to locate my static files. I have used python manage.py collectstatic to collect my static files into a staticfiles folder, but my app still doesn't seem to be able to find them. I continue to get errors like this in my log:
I'm not sure if I am referencing the paths properly. The path's that are set to images/stylesheets/scripts in the code are using the path to the original static folder used in development. Do I have to rewrite all of those paths to point to the new staticfiles folder I created with the collectstatic command, or is there some other issue that could be causing this?
My settings.py looks like this:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
DEBUG = False
ALLOWED_HOSTS = ['www.tomdeldridge.com']
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
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 = 'tomdeldridge.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['tomdeldridge/templates/tomdeldridge/'],
'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',
],
},
},
]
WSGI_APPLICATION = 'tomdeldridge.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATICFILES_DIRS = (
os.path.join(
os.path.dirname(__file__),
'static',
),
)
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
My wsgi.py file:
import os
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
application = Cling(get_wsgi_application())
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tomdeldridge.settings")
My directory structure:
The images I'm trying to reference in my template definitely exist (they work fine when I run the app locally.) I reference them like this:
{% static 'tomdeldridge/images/computer-2.png' %}
Do I have to use a server like nginx to serve static files in deployment? I am totally lost on where to go from here, and I'm not really sure why it's necessary to reconfigure the entire static file structure just to deploy.

Install dj-static package
$ pip install dj-static
Configure your static assets in settings.py:
DEBUG = False
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
Then, update your wsgi.py file to use dj-static:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tomdeldridge.settings")
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
application = Cling(get_wsgi_application())

Related

Uploaded Media files are only served after I reload the django server

I'm quite new to django development, tired of searching for this particular case of mine.
I have django app running on my windows 10 with debug = False. I am just about to deploy my app to digital ocean droplet.
I am facing so many deployment and static + media file issues. I kind of figured out static files, they are fine, media files are also loaded.
But, when I upload a new image, access it directly, it says the resource I'm looking for isn't found. But it's 100% uploaded to media/images folder, and I can see it. Today, I think I found the some solution, I can access the media files only after I reload the django server. I want to know why is that?
My settings.py file
# Application definition
INSTALLED_APPS = [
'livereload',
'mnotes.apps.MnotesConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'multiselectfield',
]
DJANGORESIZED_DEFAULT_SIZE = [100, 100]
DJANGORESIZED_DEFAULT_QUALITY = 75
DJANGORESIZED_DEFAULT_KEEP_META = True
DJANGORESIZED_DEFAULT_FORCE_FORMAT = 'JPEG'
DJANGORESIZED_DEFAULT_FORMAT_EXTENSIONS = {'JPEG': ".jpg"}
DJANGORESIZED_DEFAULT_NORMALIZE_ROTATION = True
CRISPY_TEMPLATE_PACK = 'bootstrap4'
MIDDLEWARE = [
'whitenoise.middleware.WhiteNoiseMiddleware',
'livereload.middleware.LiveReloadScript',
'django.middleware.security.SecurityMiddleware',
'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 = 'MarketingNotes.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
WSGI_APPLICATION = 'MarketingNotes.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.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/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Seoul'
USE_I18N = True
USE_L10N = True
USE_TZ = False
SESSION_COOKIE_AGE = 60 * 60 * 24 * 30
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
STATICFILES_DIRS = ( 'static/', )
print(MEDIA_ROOT)
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
LOGIN_REDIRECT_URL = '/'
LOGIN_URL = 'login'
And my wsgi.py because I changed it with WhiteNoise app for serving static + media files
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MarketingNotes.settings')
application = get_wsgi_application()
from whitenoise import WhiteNoise
application = WhiteNoise(application, root='c:/Users/Peter/Django/MarketingNotes/mnotes/static')
application.add_files('c:/Users/Peter/Django/MarketingNotes/media', prefix='media/')
Then I tried to find some way of reloading the server when the user uploads an image, it kind of seems like a bad idea though, so, now, am I supposed to figure out some linux code to reload the gunicorn server in my droplet, or does django have anything to reload the server once the media folder is changed?
Sorry for my english
UPDATE
I found the solution, it was actually django problem, I saw in some post somebody say that django doesn't serve media files in production, and for serving media files I had to configure my nginx server. So I edited /etc/nginx/sites-enabled/myapp, added media there, and as soon as new files are uploaded, nginx is serving my media files.
Thank you all.
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
Try to replace these settings in settings.py, if it doesn't works it means it's your IDE issue ..
It is related with Whitenoise.
Whitenoise only checks for static files at startup and so files added after the app starts won't be seen.
Since, Whitenose is not suitable for serving user-uploaded media files.
Please check Whitenose official docs.
http://whitenoise.evans.io/en/latest/django.html#serving-media-files

Deploying Django App to Heroku Cant load Staticfiles

I have successfully deployed my django app to heroku. but for some reason, they cant load the templates and staticfiles.
my directories are as such:
eximia (project directory)
eximia: init.py asgi.py settings.py wsgi.pyurls.py
web: templates, static: web: style.css, images: (all the images are in this folder)
and the rest of the files are normal typical django app files.
my settings.py are as follows:
Django settings for eximia project.
Generated by 'django-admin startproject' using Django 3.1.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve(strict=True).parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'sy4a^dk+1%2!g2#4s$2ihk0^9%!9or&+ycy2#0a^*qqhdksk#t'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = [
"eximia-denim.herokuapp.com"
]
# Application definition
INSTALLED_APPS = [
'web',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'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 = 'eximia.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
WSGI_APPLICATION = 'eximia.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/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/3.1/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/3.1/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
Im very new to django and this is sorta my first website. So if theres any help i would really appreciate it!! thank you! :D
To serve static files in Heroku you must use Whitenoise.
if you don't know how to use that check Heroku documentation Here
I think you have a global static folder that are not tied to any particular app.
if you have static folder inside each app, django will not have a problem to collect static files and put them inside staticfiles, but in your case you need to tell django that there is global static folder that is not tied to particular app to collect static files from it:
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)

Heroku Internal Server Error when Debug is False and collectstatic dosen't work - Django

I deployed an app to Heroku, which uses Postgres.
Anytime I set Debug to True, it works fine. When I set it back to False, it gives an Error 500, Internal Server Error. I don't know why it does that.
Does it have to do with staticfiles?
I am using whitenoise for serving static files.
Anytime I run heroku run python manage.py collectstatic, it gives me
Running python manage.py collectstatic on djangotestapp... up, run.9614 (Free)
300 static files copied to '/app/staticfiles', 758 post-processed.
When I then run heroku run bash, I find out that there is no staticfiles folder.
Where exactly does it copy the static files to?
Is this what is causing the Error 500?
How can I solve it?
settings.py
import os
import dj_database_url
from decouple import config, Csv
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
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/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config('DEBUG', cast=bool)
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 200
SECURE_HSTS_PRELOAD = True
ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast =Csv())
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
# Third-party
'allauth',
'allauth.account',
'crispy_forms',
'widget_tweaks',
'debug_toolbar',
'phonenumber_field',
'django_datatables_view',
'whitenoise.runserver_nostatic',
# Local
'users',
'pages',
'attendance',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware', # WHITENOISE
'django.middleware.common.CommonMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'djangotestapp_project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
#'DIRS': ['templates'],
'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',
],
},
},
]
WSGI_APPLICATION = 'djangotestapp_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': config('DB_NAME'),
'USER': config('DB_USER'),
'PASSWORD': config('DB_PASSWORD'),
'HOST': config('DB_HOST'),
'PORT': '5432',
},
}
prod_db = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(prod_db)
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
#STATICFILES_FINDERS = [
# 'django.contrib.staticfiles.finders.FileSystemFinder',
# 'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#]
#STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
#
# STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
AUTHENTICATION_BACKENDS = (
"django.contrib.auth.backends.ModelBackend",
"allauth.account.auth_backends.AuthenticationBackend",
)
UPDATE
I ran heroku logs -tail -a djangotestapp to view errors as they happen, and this is what it gave me.
2020-08-30T20:23:20.090560+00:00 app[web.1]: raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name)
2020-08-30T20:23:20.090560+00:00 app[web.1]: ValueError: Missing staticfiles manifest entry for 'css/font-rules-roboto.css'
The file, font-rules-roboto.css just enables me to be able to have the roboto font without any link to Google font API's.
I have run python manage.py collectstatic, but it does not do anything.
I think your problem is related to your ALLOWED_HOSTS. When you turn off the debug mode of Django's settings you must add your project host IP or domain to ALLOWED_HOSTS. So I think adding the IP of your host server to your .env file like (ALLOWED_HOSTS = localhost, ..., IP.OF.YOUR.HOST) will solve your problem.
Thank you, #Roham for your help. I solved it with an added step.
After I commented
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage', the site started working, but the static files did not load.
I then added this line to the settings, WHITENOISE_USE_FINDERS = True.
It allows your app to run without having to collectstatic files.
After I did that, all the static files loaded without any problems.

Djengo Error trying to run python manage.py test

Why am I getting this error from the end of my manange.py file? I'm trying to run python manage.py test. I get this error even if the tests.py is blank. The project works fine and I'm trying to add tests.
Error I'm getting
Sorry about the late getback, I do have django_rest in my installed apps. here's my settings.py -
"""
Django settings for djangorest project.
Generated by 'django-admin startproject' using Django 2.0.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os
# Serer datails for password reset by email
EMAIL_HOST = 'localhost'
EMAIL_PORT = 1025
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
#STATICFILES_DIR = (
# os.path.join(BASE_DIR, 'staticfiles')
#)
#STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_ROOT = (
os.path.join(BASE_DIR, 'media')
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'djangorest/media')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '04u+3)m+%o+in*5iorg*h9ze1p(tat9en8#6qkfb3#a8xty24('
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
)
}
# Custom redirect for login
LOGIN_REDIRECT_URL = '/home'
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#'django.contrib.auth.forms',
'rest_framework',
'api',
'cg',
'djangorest',
'multiselectfield',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'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 = 'api.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR,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',
],
},
},
]
WSGI_APPLICATION = 'djangorest.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.0/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.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Europe/Dublin'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
Here's my manage.py -
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangorest.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
Looks like you have failed to import rest_framework library correctly. Is there somepoint in which you are trying to import this?
do you have a anything along the lines of
INSTALLED_APPS = (
...
'rest_framework',
)
http://www.django-rest-framework.org/#installation
Would you mind posting you Manage.py? it might make it easier :)
Looks like you are missing django-rest-framework requirement.
Make sure you have it installed, you can use pip freeze command to check for installed dependencies. I guess you probably have a file named requirementes.txt or something along those lines, try with pip install -r requirements.txt to install all dependencies.
Did you add rest_framework in your setup ?
INSTALLED_APPS = [
'rest_framework',
'django.contrib.contenttypes',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

Deploy Django Static Files - Heroku

I am trying to deploy a Django site on Heroku, but I'm running into problems getting the app to locate my static files. I have used python manage.py collectstatic to collect my static files into a staticfiles folder, but my app still doesn't seem to be able to find them.
My settings.py looks like this:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
DEBUG = False
ALLOWED_HOSTS = ['www.tomdeldridge.com']
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
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 = 'tomdeldridge.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['tomdeldridge/templates/tomdeldridge/'],
'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',
],
},
},
]
WSGI_APPLICATION = 'tomdeldridge.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATICFILES_DIRS = (
os.path.join(
os.path.dirname(__file__),
'static',
),
)
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
My wsgi.py file:
import os
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
application = Cling(get_wsgi_application())
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tomdeldridge.settings")
My directory structure:
The images I'm trying to reference in my template definitely exist (they work fine when I run the app locally.) I reference them like this:
{% static 'tomdeldridge/images/computer-2.png' %}
But I get an error that looks something like this:
I'm not sure if I am referencing these paths properly during deployment though. The path's that are set to images/stylesheets/scripts in the code are using the path to the original static folder used in development. Do I have to rewrite all of those paths to point to the new staticfiles folder I created with the collectstatic command? That seems like an unnecessary hassle...
Or do I have to use a server like nginx to serve static files in deployment? I am totally lost on where to go from here, and I'm not really sure why it's necessary to reconfigure the entire static file structure just to deploy.
I'd rather add this as a comment but my karma prevents me from doing so;
My initial observation would be that the permissions aren't set correctly, so the server can't find the files correctly.
Do the files/folder have the same permissions as the development server?
One other question, does the os.path.dirname(__file__) correctly resolve to the project directory? Your BASE_DIRis referencing the same place, so try printing this on startup by putting:
print "BASE Directory:", BASE_DIR
On startup this should print out the directory its looking at as your project folder.
Check these both these things first and let me know the results of the above printout.
Edit, I'm not too familiar with Heroku but I'm starting with the basics (nima's solution below might work).

Categories

Resources