Django static files not working on Heroku - python

My django application is working well on local server. But, when I deploy it on Heroku, the static files are not being served (getting a 404 error). Please help!
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = patterns('',
url(r'^$', 'product.views.home', name='home'),
url(r'^admin/', include(admin.site.urls)),
)
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
static files settings:
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "static", "media")
STATIC_ROOT = os.path.join(BASE_DIR, "static", "static_root")
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static", "static_dirs"),
)
WSGI file -
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "acton.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
try:
from dj_static import Cling
application = Cling(get_wsgi_application())
except:
pass

This is my setting for static files to deploy on Heroku.
Hope it will help :
import os
BASE_DIR = os.path.dirname(os.path.abspath(file))
STATIC_ROOT = 'staticfiles'
STATIC_URL ='/static/'
MEDIA_ROOT = os.path.join(PROJECT_PATH, "media")
MEDIA_URL = "/media/"
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)

Your setting.py file is incorrectly configured.Static and media files should be
STATICFILES_DIRS = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

For anyone else that comes across this problem, for me it was that I was missing the whitenoise configuration from my wsgi.py file.
Specifically the following was missing from my wsgi.py file:
from whitenoise.django import DjangoWhiteNoise
application = DjangoWhiteNoise(application)
Docs are here: http://whitenoise.evans.io/en/stable/

Related

Django Backend Image not displaying

I've tried many ways but nothing works.
I can't find a solution to this issue.
My frontend is React and My backend is Django.
On browser only show the URL path link of the image instead of an image.
I've tried to add this code to another template and It was working but this one does not work.
browser display
My settings.py file:
INSTALLED_APPS = ['django.contrib.staticfiles',]
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
My urls.py file:
from django.views.generic import TemplateView
from django.urls import path, include, re_path
from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
if not settings.DEBUG:
urlpatterns += [re_path(r'^.*',
TemplateView.as_view(template_name='index.html'))]
My Model looks like this
class Product(models.Model):
name = models.CharField(max_length=200)
image = models.ImageField(blank=True)
description = models.TextField()
price = models.DecimalField(max_digits=9, decimal_places=2)
createdAt = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f" '{self.name}' "
this is my configuration, in my project React within Django, hope that could help
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATICFILES_DIRS = [
BASE_DIR / 'static',
BASE_DIR / 'frontend/build/static' //this is from react, frontend is the React project's name
]
MEDIA_ROOT = BASE_DIR / 'static/media'
STATIC_ROOT = BASE_DIR / 'staticfiles
dont forget to add/install corsheader(add it in INSTALLED_APPS also),and whitenoise
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
...]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
CORS_ALLOW_ALL_ORIGINS = True
urls.py
urlpatterns = [
path('', TemplateView.as_view(template_name='index.html')),
.....
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Django Unable to load static files - internal-nginx-static comes in URL

Hope you are all having a very good Friday!
I am running a django project on nginx, and my project is each time going into this url - https://sitename.com/internal-nginx-static-location_uat/project_name/static/images/success.svg
I didn't configure this internal-nginx-static, and If I load the same project on another website, it works fine, is it something I can handle in code, or I have make changes in server conf.
Here is my URL.py Files
from django.conf import settings
from django.contrib import admin
from django.conf.urls.static import static
from django.urls import path, include
urlpatterns = [
path('', include('portal.urls')),
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
and settings file
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(DATA_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

Django static files urls setting

Please help me check my static setting
when Debug =False,it works well
But when Debug=True,It can't catch the static files
Please help me, Thank you.
Here is my settings.py:
DEBUG = False
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = ['*']
STATIC_URL = '/static/'
STATIC_ROOT = 'static'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
urls.py
from django.conf import settings
urlpatterns = patterns('',
url(r'', include('core.urls', namespace='core')),
)
if settings.DEBUG is False:
urlpatterns += patterns('',
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
)
else:
from django.conf.urls.static import static
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
If you will write the below code in urls.py it will work for both the DEBUG status
url( r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT } ),
and one thing to be noted my static root is like for django 1.4+
PROJECT_DIR = os.path.dirname(os.path.dirname( __file__ ))
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
along with this you need to do the following command to copy all static files to PROJECT_PATH/static dir
python manage.py collectstatic

Static Files With Django Development Server 1.7 Slightly Different Directory Settings

This is my website directory:
django_project
\bin
\include
\lib
\src
\django_project
settings.py
\app2
manage.py
\static
\js
\css
\media
\templates
base.html
What I have added to my settings.py is:
STATIC_URL = '/static/'
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), "templates"),
)
if DEBUG:
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static"),
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media"),
STATICFILES_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), "static"),
),
and to my urls.py:
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
and hey, it does'nt work. The way I refer to them in the base.html is:
<link href="/static/css/bootstrap.min.css" rel="stylesheet">
Any ideas?
Thank you.
Hasan
Running the settings that you've pasted gave me an error ImproperlyConfigured: The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting. Commenting-out os.path.join(os.path.dirname(BASE_DIR), "static"), in the settings removed the error and the template correctly found the CSS file without the URLs.py modifications.
First of all as #r---------k mentioned, I should not have had trailing commas except for the tuples. So the settings.py should look like:
if DEBUG:
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static")
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media")
STATICFILES_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), "static", "static")
),
And the second thing is that, as you may notice, STATIC_ROOT and STATICFILES_DIRS cannot possibly have the same value. I added another static folder inside the static folder and put my js and css folders inside of it:
STATICFILES_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), "static", "static")
),
The directory looks like:
django_project
\bin
\include
\lib
\src
\django_project
settings.py
\app2
manage.py
\static
\static
\js
\css
\media
\templates
base.html
Finally, you should have the urlpatterns in your urls.py:
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This seems to work in current django (2.2) in your urls.py:
from django.conf import settings
from django.conf.urls.static import serve
from django.urls import include, path
urlpatterns += [
path(settings.STATIC_URL[1:], serve, {'document_root': settings.STATIC_ROOT })
]
Remember to run ./manage.py collectstatic to collect the static files to settings.STATIC_ROOT

Displaying image source from MEDIA_ROOT

I have my media_root path set to
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'media')
MEDIA_URL = 'media/'
with my project structured as so
Project_Name/
media/
profiles/
App_Name
when I try to reference the images in my profiles/ directory, I get 404 no resource found errors.
src="{{ MEDIA_URL }}{{ result.photo }}">
This resolves to http://127.0.0.1:8000/media/profiles/image1.jpg cannot be found. Am I missing absolute path, I am using DJango 1.4, I do not have the media root set in my urls.py but I didn't with my STATIC_URL definitions and I am able to find my static resources?
This is the main path of your project
PROJECT_ROOT = os.path.join(os.path.dirname(__file__), '..')
SITE_ROOT = PROJECT_ROOT
In here, the system call your media folder path where uploaded images store
MEDIA_ROOT = os.path.join(SITE_ROOT, 'media')
MEDIA_URL = '/media/'
In here are your static files where css/js/img/ ... store
STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
STATIC_URL = '/static/'
Additional location for staticfiles
STATICFILES_DIRS = (
os.path.join(SITE_ROOT, 'staticfiles'),
)
urls.py
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from project_name import settings
admin.autodiscover()
urlpatterns = patterns('',
.........
.........
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
Here is the answer
Images from media folder is not displaying django template

Categories