Django STATIC FILES not loading in actual Production - django

I have tried many things to solve this like adding whitenoise middleware, also added STATICFILES_DIRS = [], added mimetypes for css
in settings.py file CSS/JS Won't load.
Here is my settings.py
from pathlib import Path
import environ
import mimetypes
mimetypes.add_type("text/css", ".css", True)
BASE_DIR = Path(__file__).resolve().parent.parent
MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'static'
env = environ.Env()
environ.Env.read_env()
STRIPE_PUB_KEY = env('STRIPE_PUB_KEY')
DEBUG = True
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'users',
'addresses',
'orders',
'feedback',
'message',
'gifts_coupons',
'core',
'product',
'fulfillment',
'cart',
'discounts',
'stripe_pay',
'rest_framework',
'rest_framework.authtoken',
'phonenumber_field',
'django_filters',
'creditcards',
'mptt',
'corsheaders',
'import_export',
'django_inlinecss',
]
IMPORT_EXPORT_USE_TRANSACTIONS = True
AUTH_USER_MODEL = 'users.User'
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOWED_ORIGINS = [
'https://estreetmart.in',
'https://estreetmart.sg',
'https://ims.estreetmart.in',
'http://localhost:8000',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'orders.middlewares.cart_middleware',
]
ROOT_URLCONF = 'estreetmart.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 = 'estreetmart.wsgi.application'
...
I also added following in my main urls.py
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
but still css/js is not loading so I inspected the code and found following:
403 Forbidden error for static file
and also sources is empty:
Sources are empty

For static files use STATIC_URL and STATIC_ROOT. Add to your main urls.py
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Actually in my Nginx server file I commented following section and it worked
location /static/ {
...
}

Related

Error when adding AUTH_USER_MODEL to settings.py in DJANGO

i'm getting a "simple" trouble when I try to add AUTH_USER_MODEL constant to settings.py. It returns this error, but when I look to INSTALLED_APPS the app name that I'm still working is there. Here it is:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'PMEapp',
]
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
BASE_DIR = Path(__file__).resolve().parent.parent
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',
'PMEapp',
]
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 = 'SOSpme.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 = 'SOSpme.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
STATIC_URL = 'static/'
MEDIA_URL = "imgs/"
MEDIA_ROOT = os.path.join(BASE_DIR, "imgs")
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static/"),
)
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
LOGIN_URL = "login"
LOGIN_REDIRECT_URL = ""
LOGOUT_REDIRECT_URL = "login"
DATE_INPUT_FORMATS = ('%d/%m/%Y','%d-%m-%Y','%Y-%m-%d')
AUTH_USER_MODEL = "PMEapp.User"
This is the error:
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'PMEapp.User' that has not been installed
My installed apps
My file system
The user model -> It is in models.py
These are the things I've tried to solve the problem:
1-Created a User file including all user types in PMEapp folder with user inside didn't work.
2-Moved User file to a folder called User, got the same error.
3-Put all user types in models.py but User(AbstractUser) was still in User.py . Didn't worked too.
4-I've added a User.py file in models folder and imported it to the file that got all the user types. Same error.
It looks like you forgot to add an init.py file to your models directory. Try adding that and startup your Django server again. You might need to import your models in your init file, like from .models import User

Django 4.1 not identifying static file

I'm a beginner with Django and have been working a small project that requires quite a bit of styling. However, for some reason, Django isn't picking up on my static css file.
settings.py
from pathlib import Path
TEMPLATES_DIR = Path(BASE_DIR) / 'templates'
STATIC_DIR = Path(BASE_DIR) / 'static'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'CalculatorApp'
]
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 = 'Calculator.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 = 'Calculator.wsgi.application'
...
STATIC_ROOT = Path(BASE_DIR) / 'static'
STATIC_URL = 'static/'
STATICFILE_DIRS = [
STATIC_DIR,
]
I double checked my spelling, settings.py directory, checked countless posts and can't seem to find a solution. This is my first time using stack overflow, so I'm assuming I just upload pictures of my code.
Edit: here are is my views.py and urls.py.
# Urls.py
from django.contrib import admin
from django.urls import path
from CalculatorApp import views
urlpatterns = [
path('', views.index, name='index'),
path('admin/', admin.site.urls),
]
# Views.py
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request, 'index.html')

Refused to apply css styles in my Django App, because its MIME type its not supported

I have a serious problem with my Django application and is that I do not load the styles in my app, the error I get in console is as follows:
"It has been rejected to apply the style of 'http://127.0.0.1:8000/static/static/css/styles.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled".
Failed to load resource: the server responded with a status of 404 (Not Found)
Settings.py:
from email.mime import application
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
import os
DEBUG = True
ALLOWED_HOSTS = ["*"]
STATIC_URL = '/static/'
# STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
MEDIA_URL = 'Imagenes/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'Imagenes')
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'ckeditor',
'clase',
'index',
'accounts',
]
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 = 'djanpro.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',
],
},
},
]
...
this is urls.py file:
from xml.dom.minidom import Document
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from djanpro.settings import MEDIA_ROOT
urlpatterns = [
path('', include("index.urls")),
path('clase/', include("clase.urls")),
path("accounts/", include("accounts.urls")),
path('admin/', admin.site.urls)
]+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
for now I can only view the html of my platform, however the images that are saved in the posts seem to be working.

Django - images uploaded by user does not display and shows 404 when Debug = False

I am developing a Django and using ImageFiled attributes into models that I need to display later. When I run the website in dev (DEBUG = True) it works, but when I change it to False (Production) uplaoded images do not display anymore and the console shows:
"GET HTTP/1.1" 200
As I saw in other open questionsI tried to add in settings:
MEDIA_ROOT = os.path.join(BASE_DIR, 'images')
and in urls
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
But this doesn't work and even creates the same issue as in production.
settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'home.apps.HomeConfig',
'gallery.apps.GalleryConfig',
'storages',
]
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',
'django.middleware.locale.LocaleMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
]
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',
],
},
},
]
DEBUG = False
if not DEBUG:
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_URL = 'static/'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
db_from_env = dj_database_url.config()
DATABASES['default'].update(db_from_env)
Update:
The documentation says:
URL that handles the media served from MEDIA_ROOT, used for managing stored files. It must end in a slash if set to a non-empty value. You will need to configure these files to be served in both development and production environments.
If you want to use {{ MEDIA_URL }} in your templates, add 'django.template.context_processors.media' in the 'context_processors' option of TEMPLATES.
https://docs.djangoproject.com/en/1.8/ref/settings/#media-root----
I tried this and the problem is still there.
I normally set these in the urls.py for the project to handle media and static files correctly.
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT).
I think you are missing the settings.DEBUG if statement in urls.py config.
The problem has been solved by using AWS storage instead of the server storage.
Effectively, as been said in the answers Django is not optimised to server static/media.

Django-ckeditor file upload doesn't work

I use django-ckeditor module in my blog as WYSIWYG editor for create and edit articles in the administration. It work pretty well but I can't upload image to my server. When I click on the image button, the button "browse the server" and "upload image" doesn't appear as they supposed to (I saw it somewhere). I can only add externals images providing their urls.
I use Django 1.8 with Python 3.4
The module django-ckeditor and ckeditor_uploader are correctly installed and added in the INSTALLED_APP.
This is my settings.py file :
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
'ckeditor',
'ckeditor_uploader',
)
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-mini-blog.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',
'django.template.context_processors.media',
],
},
},
]
WSGI_APPLICATION = 'django-mini-blog.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
LANGUAGE_CODE = 'fr-fr'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
CKEDITOR_UPLOAD_PATH = "uploads/"
CKEDITOR_IMAGE_BACKEND = "pillow"
Thanks in advance for your help.
Sincerely,
Did you add the following code to your urls.py file?
urlpatterns = patterns(
'',
....
(r'^ckeditor/', include('ckeditor.urls')),
)