My Django template cant seem to find my css file in my static folder which is structured at the root dir.
Here is my settings.py
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-j#g&qm&20_oct_3f*sn-7n117si&1x4+m9cjao%g_&88gtmk9&'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'maintenance',
'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 = 'nitrofleet.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [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 = 'nitrofleet.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',
}
}
# 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 = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIR = [ BASE_DIR/'static']
STATIC_ROOT = ["static_root"]
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
and my urls.py
from django.contrib import admin
from django.urls import path
from django.urls.conf import include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('maintenance/',include('maintenance.urls'))
]
if settings.DEBUG :
urlpatterns += static(settings.STATIC_URL,document_root =settings.STATIC_ROOT)
and my template (also settings in the root dir) :
{%load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}" />
</head>
<body>
<div class='test'> turn this red </div
</body>
</html>
lastly the css file (setting in the root dir as static > css > styles.css)
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
.sidebar{
width: 70px;
background-color: #73879c;
}
.test{
color:red;
}
on making a get request ill receive this :
[15/Dec/2021 12:36:37] "GET /static/css/styles.css HTTP/1.1" 404 1902
Instead of STATICFILES_DIR = [ BASE_DIR/'static']
Try using
STATICFILES_DIRS = [
os.path.join(BASE_DIR, '/static') ]
Change this in your settings.py:
STATIC_ROOT = ["static_root"]
To this (of course, if your static folder name is "static"):
STATIC_ROOT = BASEDIR / "static"
In STATIC_ROOT you should set:
BASEDIR + folder name, where your static files are.
STATICFILES_DIR = [ BASE_DIR/'static']
here you has to finish line with comma, because is a list
STATICFILES_DIR = [
BASE_DIR/'static',
]
Related
Not able to load image from static dir in Django. Below is the picture of my file structure.
In settings.py S
STATIC_URL = '/static/'
STATICFILES_DIR = [
os.path.join(BASE_DIR,'static')
When I try to load the image file from STATIC_URL, it is producing this error:
it is just not loading images but the text from my home-view.html is loading file thus django is not able to locate the image files. Could you please advise why are images not loading?
home-view.html
{% load static %}
<html>
<head>
{{time}}
<img src="{% static 'myproject/images/test.png' %}" alt="My image">
</head>
</html>
My complete settings.py file :
"""
Django settings for myproject project.
Generated by 'django-admin startproject' using Django 4.0.4.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
print("Path is : ", os.path.join(BASE_DIR, 'myproject/template'))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-(ep(j)h+$(zro2!9r3bm0fj^!84-1c9d+)$be4hgrq4_#6d^r-'
# 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',
'myproject'
]
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 = 'myproject.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'myproject/template')],
'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 = 'myproject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.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/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIR = [
os.path.join(BASE_DIR,'static')
]
print("static path" , STATICFILES_DIR)
print(STATIC_URL)
# print("static file : ", (os.path.join(BASE_DIR, '/static')), )
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
instead of this:
STATICFILES_DIR = [os.path.join(BASE_DIR,'static'),]
Do this and try:
STATICFILES_DIRS = [os.path.join(BASE_DIR,'appname/static'),]
and also add this:
os.path.join(BASE_DIR, 'appname', 'templates')
{% load static %}
<html>
<head>
{{time}}
<img src="{% static '/myproject/images/test.png' %}" alt="My image">
</head>
</html>
and make sure you create folder called templates instead of template
I hope this may be help you
My problem is that the admin panel is not displayed correctly in the chrome browser (for example, everything is fine in yandex). Several windows seem to overlap each other and work with the panel becomes impossible. This has happened since the beginning of the project. At the same time, everything seems to be fine with the styles. I would be very grateful for any help!
URLs.py:
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
url(r'^accounts/', include('Вход.urls')),
url(r'^admin/', admin.site.urls),
url(r'^', include('Главная.urls')),
url(r'^Новости/', include('Новости.urls')),
url(r'^Видео/', include('Видео.urls')),
url(r'^Фото/', include('Фото.urls')),
url(r'^Аудио/', include('Аудио.urls')),
url(r'^Документы/', include('Документы.urls')),
url(r'^О_нас/', include('О_нас.urls')),
]
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns() + static(
settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Settings.py:
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/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
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'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 = 'Крылья_веры.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 = 'Крылья_веры.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',
}
}
# 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 = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
Problem
I am naive in Django. Trying out a few pieces of stuff here. I was working with static files and have got stuck here. Please help me out here.
I am very much confused about static_root and static_dirs. I am following an online tutorial where the static root has not been used and their project is working fine. If am trying that I facing lots of errors and exceptions.
Here is my view:
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
my_dict={'insert_me':"Hello I am from views.py"}
return render(request,'first_app/index.html',context=my_dict)
Here is my projects urls:
from django.contrib import admin
from django.conf.urls import url
from django.conf.urls import include
from first_app import views
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^first_app/',include('first_app.urls')),
url(r'^admin/', admin.site.urls),]
urlpatterns += staticfiles_urlpatterns()
Here is my apps url:
from django.conf.urls import url
from first_app import views
from django.contrib import admin
urlpatterns= [
url(r'', views.index, name='index'),]
the index.html:
{% load staticfiles%}
<html>
<head>
<meta charset="utf-8">
<title>DJ Page</title>
</head>
<body>
<h1>Hello this is index.html!</h1>
<img src="{% static 'images/dj.jpg'%}" alt='oh oh! did not show'>
</body>
</html>
and here is my setting:
"""
Django settings for Twenty3rdMrach project.
Generated by 'django-admin startproject' using Django 2.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATES_DIR=os.path.join(BASE_DIR,'templates')
#TEMPLATES_DIR=os.path.join(TEMPLATES_DIR,'first_app')
print(TEMPLATES_DIR)
STATIC_DIR=os.path.join(BASE_DIR,'static')
print (STATIC_DIR )
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'mz^^exko#!2czk35u$w-qr&v8u(46(fp7#u41ctabvwf=mz9m&'
# 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',
'first_app',
]
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 = 'Twenty3rdMrach.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATES_DIR,],
'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 = 'Twenty3rdMrach.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'udemy1',
'USER':'root',
'PASSWORD':'Ravi#go123',
'HOST':'localhost',
'PORT':'3306',
}
}
# Password validation
# https://docs.djangoproject.com/en/2.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/2.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/2.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIR = (os.path.join(BASE_DIR, 'static/'),)
STATIC_ROOT=os.path.join(BASE_DIR,'static_media/')
While hitting the url:
http://127.0.0.1:8000/static/images/dj.jpg
am facing the below error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/static/images/dj.jpg
Raised by: django.contrib.staticfiles.views.serve
'images\dj.jpg' could not be found
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
STATICFILES_DIR - Setting is to tell Django which directories to be scanned for static files.
STATIC_ROOT - Setting is to tell Django where to put all the static files when python manage.py collectstatic command is executed.
I think you should remove the trailing slash in STATICFILES_DIR and STATIC_ROOT
STATIC_URL = '/static/'
STATICFILES_DIR = (os.path.join(BASE_DIR, 'static'),)
STATIC_ROOT=os.path.join(BASE_DIR,'static_media')
My Djangoproject call: myDebug
and my Django app call: Deb
it is on Heroku: meindebug.herokuapp.com
settings.py
import os
import django_heroku
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx'
DEBUG = False
ALLOWED_HOSTS = ['meindebug.herokuapp.com']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Deb',
]
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 = 'myDebug.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 = 'myDebug.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
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',
},
]
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 = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
django_heroku.settings(locals())
!!! please notice i tried it with ALLOWED_HOSTS = ['*'] but nothing changed !!!
wsgi.py
import os
from django.core.wsgi import get_wsgi_application
from whitenoise import WhiteNoise
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myDebug.settings")
application = get_wsgi_application()
application = WhiteNoise(application, root='/static/Deb/Images/')
application.add_files('/static/Deb/Images/', prefix='more-files/')
Procfile
web: gunicorn myDebug.wsgi
Pipfile
[[source]]
url = "https://pypi.python.org/simple"
verify_ssl = true
name = "pypi"
[packages]
gunicorn = "*"
django-heroku = "*"
whitenoise = "*"
[dev-packages]
[requires]
python_version = "3.6"
Since two Weeks i tried to fix that issue.
Unfortunately, I was not successful.
Nowhere i find a real Fix. Only some words there and there but noone have a real Solution.
First you have to run python manage.py collectstatic.
Then in Heroku the Config Variables to COLLECTSTATIC = 1.
but the file Path to your Pictures/Files have to show like this
{% static "MyApp/Images/Picture.png" %}
you get an Error if you write it so
{% static "/MyApp/Images/Picture.png" %}
the slash at front of MyApp is the problem. So write it without slash then it works.
If you have a favicon in the head then you have to write it so
<link rel="shortcut icon" href="https://www.yourwebsite.de/static/MyApp/Images/favicon.ico">
For what it's worth, you'll face the same issue if you have an html comment in your code that calls the template tag "static" (probably the behavior is the same for every commented template tag), this was my case:
<!-- <img src="{% static 'main_website/images/image.jpg' %}" alt=""> -->
removing the comment resoled the 500 error (which also, was not being logged).
I had a same issue it appears that I had some css file linked but the original files were deleted. please make sure you aren't linking any not existing external file.
I know there are similar questions, but believe me I've gone through every each of them, but still not getting my static files going through.
Any help is greatly appreciated.
I have all my setting and other codes below.
The capture below shows when I run
$ heroku run python manage.py collectstatic
and the erorr I get when I deploy my app.
Capture
setting.py:
import os
import dj_database_url
# this is because I have my setting.py under setting folder
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
SECRET_KEY = os.environ['secret_key']
DEBUG = False
ADMINS = []
ALLOWED_HOSTS = ['*']
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = '...#gmail.com'
EMAIL_HOST_PASSWORD = os.environ['EMAIL_HOST_PASSWORD']
EMAIL_PORT = 587
EMAIL_USE_TLS = True
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.sites',
'registration',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# third party apps
'crispy_forms',
# my apps
'home',
]
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 = 'site2.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.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'site2.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
db_from_env = dj_database_url.config()
DATABASES['default'].update(db_from_env)
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',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
# registration settings
ACCOUNT_ACTIVATION_DAYS = 7
REGISTRATION_AUTO_LOGIN = True
SITE_ID = 1
LOGIN_REDIRECT_URL = '/'
# crispy form settings
CRISPY_TEMPLATE_PACK = 'bootstrap3'
Procfile:
web: gunicorn site2.wsgi --log-file -
wsgi.py:
import os
from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "site2.settings")
application = get_wsgi_application()
application = DjangoWhiteNoise(application)
urls.py:
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('registration.backends.default.urls')),
url(r'^', include('home.urls')),
]
if not settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Here is part of my template which is not loading properly:
<!DOCTYPE html>
{% load static from staticfiles %}
<html lang="en">
<head>
<!-- Custom styles for this template -->
<link href="{% static 'css/offcanvas.css' %}" rel="stylesheet">
</head>
Change in urls.py:
if settings.DEBUG is True:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Or remove static serving code in urls,because whitenose is serving static files, you don't need to serve static files from django in heroku.