Django Media not showing with Debug False - python

I'm a beginner at Python, my settings.py:
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'theme', 'static'),
]
If I turn DEBUG to False,the staticfiles and mediafiles don't work, when i run devserver in insecure mode:
python manage.py runserver --insecure
The staticfiles works,but mediafiles(avatars) still doens't work.
my app installed way:
pip install misago
start path:
/home/project/
Can someone help me?
thanks.

Django with debug false, does not manage the statics and media files.
You need to:
Add "statics root" and "media root" to your django settings.py file
Use NGINX to manage statics file (see more info about deployment on django documentation)
use "collect static" command to collect the static/media file

Related

Static files not loading on django localhost (404 error) while loading okay on heroku

Problem
I'm building a django web app. I can't get to display a static file (icon) in an html template when I run my app locally (ubuntu 20.04, python 3.8.5, django 3.1.4).
I DO NOT HAVE THIS ISSUE WHEN DEPLOYING ON HEROKU CLOUD, only on my localhost.
When loading up the webpabe on my localhost, I can see "GET /static/icons/graph-up.svg HTTP/1.1" 404 1781 in the Django wsgi console.
My project tree:
django-project
|_ ...
|_ static
|_ icons
|_ graph-up.svg
index.html
{% load static %}
<img src="{% static 'icons/graph-up.svg' %}" />
settings.py
[...]
BASE_DIR = Path(__file__).resolve().parent.parent
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# I've tried with and without whitenoise, doesnt seem to change anything
MIDDLEWARE = [
# 'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
# ...
]
[...]
urls.py
urlpatterns = [
path('', views.home, name='index'),
...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
I've followed the instructions from https://docs.djangoproject.com/en/3.1/howto/static-files/
Any ideas or suggestions welcome!
What I've tried locally so far
Without success (icon gets 404 error)
python manage.py runserver (to run with the wsgi from django)
gunicorn my_app.wsgi
heroku local (to simulate the heroku web server which is gunicorn locally)
python manage.py runserver --insecure (from Django Static files 404)
load the app locally with/without the whitenoise.middleware.WhiteNoiseMiddleware line in MIDDLEWARE after django.middleware.security.SecurityMiddleware
With partial success
Following an answer from Django Static files 404:
I replaced:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
with:
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join('static'), )
I reloaded the wsgi and voila. The icon shows up.
However when I revert back to the original
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Just to see what happens, the icon still shows up.
Conclusion
I'm not sure this is the right thing to do but it seems to be working fine. Here's how I workaround the issue.
In my settings.py (for heroku):
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
In my settings_dev.py (for localhost):
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join('static'), )
I don't know exactly what the problem is but to fix it you can use Whitenoise module, used to serve staticfiles
for Reference: https://youtu.be/kBwhtEIXGII
for in detail info.: http://whitenoise.evans.io/en/stable/

STATIC(CSS AND JS) FILES ARE NOT WORKING AFTER UPLOADING WEBSITE ON HEROKU

I have just uploaded my website on heroku, the css and javascript files works perfectly on localhost but doesn't work after deploying. I also made sure to run this command python manage.py collectstatic which i did both in the production and development environment but doesn't still solve the problem. I have included the necessary codes that would be useful, i have also included the images of both instances and my project directory
Settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/')
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
urls.py
from django.conf.urls.static import static
from django.conf import settings
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
This is the image on localhost
This is the image on heroku
And this is the the project directory structure
Django does not serve static file on production and by default, Heroku does not support this, unless you add whitenoise to your project please follow these steps hopefully it will help you
You can follow the official documentation of Heroku for serving a static file on production.
> Just replace your code with these lines
>urls.py
urlpatterns += static(settings.STATIC_URL,document_root=settings.STATICFILES_DIRS[0])
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
> settings.py
BASE_DIR = Path(__file__).resolve().parent.parent
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Make sure you run command using heroku cli:
heroku run python manage.py collectstatic

Django development server command

I am a little confused about the Django development server. Here the question is if my project running based on gunicorn and Nginx in production environment.
Should my local development need Nginx for serving static files?
if yes then what command should I use instead of Python manage.py runserver.
Help me get out of it.
For static file, you have to manage below variables in your settings.py
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'your_app_name/static')
]
For media related thing you have to set below variables in your settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

Deploying my Django website to Heroku with DEBUG=False doesn't work

When deploying django onto either localhost or heroku with DEBUG=False, it throws an error saying
C:\Users\krish\Envs\PRREMIA\lib\site-packages\whitenoise\base.py:105: UserWarning: No directory at: c:\Users\krish\Documents\python\PRREMIA\staticfiles\
warnings.warn(u'No directory at: {}'.format(root))
[28/Jul/2019 16:05:43] "GET / HTTP/1.1" 500 27
When DEBUG=True, it works fine.
STATIC SETTINGS
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
On Github
Why? And how do I stop and fix this?
Note:
Removing whitenose middleware from MIDDLEWARE and changing STATICFILES_STORAGE
# STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
removed the 500 Error, but the staticfiles are still not found.
Configure Django / Create-React-App / Whitenoise to run git deploy to Heroku App with DEBUG = False
Big thank-you to Whitenoise developers first off to make this all possible!
In your settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'staticfiles')],
'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',
],
},
},
]
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'build/static'), os.path.join(BASE_DIR, 'build')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
In views.py create a template view of index.html
from django.views.generic import TemplateView
from django.views.decorators.cache import never_cache
# Serve Single Page Application
index = never_cache(TemplateView.as_view(template_name='index.html'))
In urls.py add path to your new view
from django.urls import path, include, re_path
from .views import index
urlpatterns += [
re_path('.*', index)
]
Run npm run build and then python manage.py collectstatic before pushing to heroku. This will build your application into a build folder, and then collect these static build files into a staticfiles folder in your project root.
If python manage.py collectstatic fails, create an empty directory called staticfiles in the project root first.
The point of the index re_path view is to always point your application back to index.html when reloading a page at a path like '/login'.
git add .
git commit -m "blah"
git push heroku master
This worked for me, hopefully it helps people somewhat in the future.
If this does not work, my advice is to investigate by running python manage.py runserver locally and messing around with your build folder, staticfiles folder, and settings.py to figure out what is going on. I would also recommend logging to find the error, although I did not do this myself.
Your STATICFILES_DIRS setting is incorrect:
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
This refers to a directory called static in the root of your project, but there is no such directory.
It looks like your static files are inside the business application, in which case they will be picked up automatically so you can just remove the STATICFILES_DIRS setting altogether.

Why Django-Admin Panel did not show css and javascript in real vps?

I have django admin panel working on a vps ( Windows Server 2012 ) , Why it is not showing any css styles or boostrap ? it is showing just html and nothing else .
https://docs.djangoproject.com/en/2.1/howto/static-files/
During development, if you use django.contrib.staticfiles, this will
be done automatically by runserver when DEBUG is set to True (see
django.contrib.staticfiles.views.serve()).
So when you change DEBUG=False to move out of development, Django runserver will no longer automatically serve static files.
Here is an alternate method using http://whitenoise.evans.io/en/stable/django.html
whitenoise for serving staticfiles in deployment
1) pip install whitenoise
2) Add 'whitenoise' to installed_apps
3) Give STATIC_ROOT to a folder like:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
4) Run to collect staticfiles in STATIC_ROOT directory
python manage.py collectstatic
5)Add STATICFILES_STORAGE(optional)
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
6) Add in middleware before everything except 'django.middleware.security.SecurityMiddleware', like:
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
...
]
7)Change to DEBUG=False in settings.py
More details here http://whitenoise.evans.io/en/stable/django.html

Categories

Resources