Deploy Django Static Files - 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.
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).

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

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.

Why can't I add static files in my django project when other static files are available in sources?

I'm trying to build a Django app for Heroku and have gone through the Polls tutorial and Heroku documentation
When serving the basic Django-heroku app with heroku local or python3 manage.py runserver I can see that some static files are loaded just fine (/static/lang-logo.png specifically). But when I add my main.css and run python3 manage.py collectstatic the css file never shows up and the import in my index.html never loads.
I've ready that whitenoise is best for serving static files in a django app so I'm using that and have set my settings.py based on many of the responses to similar questions here.
Collectstatic appears to be working (see below). I've been banging my head against this for literally days and have gone through dozens of related questions here and nothing seems to cut it. I have reached the end of the internet and now you are my only hope. My code is below and I'll update the question if I realize I've missed something relevant.
Settings.py
"""
Django settings for gettingstarted project.
Generated by 'django-admin startproject' using Django 2.0.
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
import django_heroku
import fred
# 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.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'CHANGE_ME!!!! (P.S. the SECRET_KEY environment variable will be used, if set, instead).'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'hello'
]
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',
'whitenoise.middleware.WhiteNoiseMiddleware',
]
ROOT_URLCONF = 'gettingstarted.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 = 'gettingstarted.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 = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = 'hello/static/hello'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'hello/static/hello'),
)
django_heroku.settings(locals())
index.html
{% load staticfiles %}
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'hello/screener.css' %}" />
Directory structure
/hello/static/hello/index.css
collectstatic output
Post-processed 'hello/screener.css' as 'hello/screener.4d9ca1ef5004.css'
Post-processed 'screener.css' as 'screener.4d9ca1ef5004.css'
121 static files copied to '/Users/user/Desktop/heroku-bayesian/python-getting-started/staticfiles', 151 post-processed.
Change your STATIC_URL to /static/ and for testing purposes, just set your STATICFILES_DIR = ['hello/static/hello']. Whitenoise does not necessarily need to be 2nd. I run mine on the bottom and it works fantastic with my Django multi-tenant app on Heroku. I believe when you push to Heroku now, you will probably have to do a collectstatic again. If it complains about your static files when building after the first time, just disable it like Heroku says here.
Edit: By the way SQLite is not supported by Heroku and you will need to migrate over to postgres. This is something I did and never looked back. All you have to do is change the database information and engine and you are good to go.

Static files not found - Deploying Django on 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. 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())

Django 1.8: Help making filenames RELATIVE

I'm new to Django. First I'll explain my issue and my logic. I want to make my filepaths RELATIVE as opposed to the ABSOLUTE they are now so I can work on my laptop and PC and have everything show up as is.
I know I'll have to alter MEDIA_URL in the settings.py below. Does
MEDIA_URL = os.path.join(BASE_DIR, 'articles/static/articles/media/')
STATIC_URL = os.path.join(BASE_DIR, 'articles/static/')
make sense? I mean logically to me its saying from BASE_DIR which prints to C:\Users\kevIN3D\Documents\GitHub\articleTestProject\articleTestSite, would step into articles/static/articles/media/ or does the fact that
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
is abspath(...) change everything?
settings.py
"""
Django settings for articleTestSite project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
MEDIA_ROOT = 'C:/Users/kevIN3D/Documents/GitHub/articleTestProject/articleTestSite/articles/static/articles/'
MEDIA_URL = '/media/'
# 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 = '2u#9=qkari39(465g+u!2t7*9tt_pdv)%155jdgxnki5#jujje'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'articles',
'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 = 'articleTestSite.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',
],
},
},
]
WSGI_APPLICATION = 'articleTestSite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC-5'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_ROOT = 'C:/Users/kevIN3D/Documents/GitHub/articleTestProject/articleTestSite/articles/'
STATIC_URL = '/static/'
urls.py
urlpatterns = [
url(r'^articles/', include('articles.urls')),
url(r'^$', HomePage.as_view(), name='home'),
url(r'^admin/', include(admin.site.urls)),
] + static(settings.MEDIA_ROOT)
My issue is when I try to use '/' in my declaration it prints out the filename as 'C:\Users\kevIN3D\Documents\GitHub\articleTestProject\articleTestSite\articles/static/' so it uses incorrect slashes for myself.
How do I go about making my page have relative filenames? I want to be able to work on this between my laptop and my PC, but as it currently stands I can only work on it on my PC because all the filenames are absolute and just give me broken links on my laptop.
Here is a link to the repository Github Repository. Please any help would be appreciated, I'm completely stumped. If someone could get that working, with images and custom CSS and then kind of walk me through what you did. Its my first time trying to distribute a Django file to more then just the local host.
Let me explain settings:
Right wave to separate the path
Pass every folder to the os.path.join() method. Example:
os.path.join(BASE_DIR, 'articles', 'static')
STATIC_URL, MEDIA_URL
This variables are passed to your template context proccessor (if you use django.template.context_processors.media) without any changes. This variables are used to make client-side links to your static and media content.
You should set your STATIC_URL and MEDIA_URL manually. Like that:
STATIC_URL = "/static/"
MEDIA_URL = "/media/"
Then you can use them in templates:
<img src="{{STATIC_URL}}img/logo.png">(...)
STATIC_ROOT, MEDIA_ROOT, STATICFILES_DIRS
STATIC_ROOT is used to bring all your static files in one place by collectstatic command (if you're using django simple server, you shouldn't care about it).
STATICFILES_DIRS is the folder when your django simple server (manage.py runserver command) gets files to serve. If you will run collectstatic command, evety file from every dir listed in STATICFILES_DIRS copied be moved in STATIC_ROOT.
MEDIA_ROOT is the folder where Django will hold user-uploaded files (ImageField, FileField)
You should use absolute path in STATIC_ROOT, MEDIA_ROOT, STATICFILES_DIRS:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATIC_ROOT = os.path.join(BASE_DIR, 'media')
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'example', 'static', 'folder',)
Please note. If you have static folder in your app folder and your app is listed in INSTALLED_APPS this folder will be added to your STATICFILES_DIRS automatically.
Serving static and media files during development
It's really simple just add this lines after your urlpatterns:
urlpatterns = patterns('',
... your patterns...
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And don't forget to include settings:
from django.conf import settings
Serving on production server
Run collectstatic command to bring all your static content in one place.
Server your static and media folder using your apache/nginx/etc server:
Alias /media/ /path/to/your/media
Alias /static/ /path/to/your/static/
So I think I figured it out,
I was looking at things far to high-level so to speak. When in reality the answer was just simple. After giving myself a
print(BASE_DIR)
and having it spit out C:\Users\kevIN3D\Documents\GitHub\articlesTestProject\articleTestSite I realized all I needed to do was append that to my different ROOT variables.
MEDIA_ROOT = 'C:/Users/kevIN3D/Documents/GitHub/articleTestProject/articleTestSite/articles/static/articles/'
was my old MEDIA_ROOT, this was clearly absolute. BUT from this I can see that it shares that same filepath as BASE_DIR, so I went from there and
MEDIA_ROOT = 'C:/Users/kevIN3D/Documents/GitHub/articleTestProject/articleTestSite/articles/static/articles/'
became
MEDIA_ROOT = os.path.join(BASE_DIR, 'articles/static/articles/').replace('\\', '/') #run replace to convert UNIX slashes on Windows slashes
I had to do the same thing for STATIC_ROOT
STATIC_ROOT = 'C:/Users/kevIN3D/Documents/GitHub/articleTestProject/articleTestSite/articles/'
became
STATIC_ROOT = os.path.join(BASE_DIR, 'articles')

Categories

Resources