Static files status' 404 - django

I'm using heroku to host my Django(1.6) app (called 'Zen'). The problem is static files aren't showing. In other words, there's no CSS and no JS in my app because it doesn't found those files. I looked to other questions here and I configured my app as below:
Settings.py:
##### Static asset configuration #####
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
urls.py:
from django.conf.urls.static import static
from zen import settings
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += patterns('',
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
)
wsgi.py:
import os
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "zen.settings")
application = Cling(get_wsgi_application())
Apparently, after pushing my app with git push heroku master all is working great:
-----> Preparing static assets
Running collectstatic...
69 static files copied to '/app/staticfiles'.
But as you can see there is no CSS in my app (http://obscure-reef-8874.herokuapp.com/). I looked to my app's log and mostly css and js files are in 404 status... I tried everything, can you help me?
EDIT:
I didn't find the bug, I recreated an app and it worked, simple.

Set
STATIC_ROOT = 'static'
try
May be caused by different STATIC_ROOT and STATICFILES_DIRS

The problem is not with your static file serving: that is fine, as you can see if you go to the admin application: http://obscure-reef-8874.herokuapp.com/admin/. Files under /static/admin/ are being served with no problem.
Without seeing the structure of your application and the way you are outputting the static links in your template it's hard to help, I guess that your files are inside a subdirectory of /static/, so you'll need to reference that subdirectory in the links to the assets in your template.
Note that you should remove the additional static URL patterns from your urls.py. They do not work when DEBUG is False. Your files are served by Cling, which is external to Django.

Related

Django dev server STILL won't serve static files

Okay, all. I know this is a question that many people have solved in various cases, but I cannot for the life of me get my Django 1.9 development server to serve static content on my local computer. Static files worked fine pre-deployment, and are totally fine on my deployment server, but now in my test environment (local computer with runserver going) everything is broken, and I really need to be able to test stylesheets in a dev environment.
I have tried all of these solutions and more, followed the documentation guide, used collectstatic again in the development repo... nothing has worked, and I am at my wits' end.
Currently, I have DEBUG = True, and the following setup:
Folder Hierarchy
project/
manage.py
(&c)
app/
urls.py
models.py
(&c)
project/
settings.py
urls.py
(&c)
static/
styles/
images/
(&c)
settings.py Static Files Settings
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = (
os.path.join(STATIC_ROOT, 'styles/'),
os.path.join(STATIC_ROOT, 'js/'),
os.path.join(STATIC_ROOT, 'audio/'),
os.path.join(STATIC_ROOT, 'images/'),
os.path.join(STATIC_ROOT, 'admin/'),
os.path.join(STATIC_ROOT, 'documents/'),
)
urls.py URL Patterns
from django.conf.urls import include, url, patterns
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
urlpatterns = [
# ... project url patterns blah blah ...
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += patterns('', (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root':settings.STATIC_ROOT, 'show_indexes': True}))
I also have {% load staticfiles %} in my templates along with the appropriate {% static %} calls (ex: {% static 'styles/main.css' %}).
For reference, the command line gives me the following when I load the page:
"GET /static/styles/main.css HTTP/1.1" 404 1759
If anyone knows of a fix I have missed that might even remotely have a snowball's chance of working, please let me know. It's driving me bonkers not being able to test properly.
EDIT: As suggested, I have updated to Django 1.11 on my local machine, with no changes to the current issue.
I'm not able to test it out, but maybe try changing this:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
to this:
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
By the way, version 1.9 is unsupported and also a security risk. You'd probably want to upgrade to another version.
Can you try to create the STATIC_ROOT var with the absolute path and check if it works?
Maybe the construction of that var is not OK.
You could also check the STATIC_ROOT var through
python manage.py shell
and see if it correctly fits your path.

Django local development static files 404 [duplicate]

I am using Django with runserver for my development. When I deploy to my production server I can see all my static files, but not on my local computer.
I did collectstatic and I have set DEBUG = True.
I found many different opinions online, the most prominent being the STATICFILES_DIRS, but that does not work for me.
How can I set it so that in my development environment I can see the static files, and when I upload my files to the server I do not need to make any changes for the production environment to work properly.
Edit - my urls.py file:
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
import newsflashes
import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('newsflashes.urls')),
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Edit - file structure:
I have two directories, static and dynamic. Inside static are the static files, and in the dynamic directory are the django apps.
Edit - Settings:
My relevant settings are as follows
STATIC_ROOT = os.path.join(BASE_DIR, '..', 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = ()
I managed to fix it.
I created another directory called static in my project folder called static, and copied there my static files.
I then added:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
import settings
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
to my urls.py
and
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
to my settings.py.
Then, when I deploy I execute manage.py collectstatic and since Apache is configured properly, everything will work!
Based on http://dlo.me/archives/2013/01/14/how-to-serve-static-files-django/
Thanks to all.
I usually run python manage.py runserver --insecure to force serving of static files with the staticfiles app even if the DEBUG setting is False.
Here's the link of their documentation. https://docs.djangoproject.com/en/3.2/ref/contrib/staticfiles/#cmdoption-runserver-insecure

Django runserver not serving static files in development

I am using Django with runserver for my development. When I deploy to my production server I can see all my static files, but not on my local computer.
I did collectstatic and I have set DEBUG = True.
I found many different opinions online, the most prominent being the STATICFILES_DIRS, but that does not work for me.
How can I set it so that in my development environment I can see the static files, and when I upload my files to the server I do not need to make any changes for the production environment to work properly.
Edit - my urls.py file:
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
import newsflashes
import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('newsflashes.urls')),
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Edit - file structure:
I have two directories, static and dynamic. Inside static are the static files, and in the dynamic directory are the django apps.
Edit - Settings:
My relevant settings are as follows
STATIC_ROOT = os.path.join(BASE_DIR, '..', 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = ()
I managed to fix it.
I created another directory called static in my project folder called static, and copied there my static files.
I then added:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
import settings
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
to my urls.py
and
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
to my settings.py.
Then, when I deploy I execute manage.py collectstatic and since Apache is configured properly, everything will work!
Based on http://dlo.me/archives/2013/01/14/how-to-serve-static-files-django/
Thanks to all.
I usually run python manage.py runserver --insecure to force serving of static files with the staticfiles app even if the DEBUG setting is False.
Here's the link of their documentation. https://docs.djangoproject.com/en/3.2/ref/contrib/staticfiles/#cmdoption-runserver-insecure

Configuring Django runserver to serve static files in a non-app directory?

I'm trying to configure Django to serve static files when using runserver (production works fine). Everything works fine for all of the static files that are under an apps directory. The problem comes with static files that are not under a specific app, but are in the final static directory. For instance, I have this project structure:
/myproject/
/myproject/static/
/myproject/static/css/foo.css
/myproject/app1
/myproject/app1/static/css/bar.css
urls.py
if settings.SERVE_STATIC:
urlpatterns += patterns('',
url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_ROOT}),
)
urlpatterns += staticfiles_urlpatterns() # one of these may be redundant.
settings.py
SERVE_STATIC = True
PROJECT_ROOT = '/myproject'
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(PROJECT_ROOT, 'static'),)
INSTALLED_APPS = ('app1',)
With these settings, I get the error:
ImproperlyConfigured: The STATICFILES_DIRS setting should not contain
the STATIC_ROOT setting
Which makes sense. I'm telling Django to collect static files, and put them in the same place - which could cause a loop.
If I comment out the STATICFILES_DIRS variable, django will find the static file 'bar.css'. But it does not find 'foo.css'.
If I comment out the STATIC_ROOT variable and put back the STATICFILES_DIRS, then it finds the file 'foo.css' - but of course, the 'collectstatic' command will no longer work.
Note - I realize that the '/static' directory is supposed to be empty, but the project I'm on, has files there anyway. :) As long as they're not overwritten by 'collectstatic', it looks like Django runserver should serve them - but it doesn't.
How do I serve the static files under STATIC_ROOT (such as foo.css) when running Django runserver?
Move the files that are in /static/ right now to a different directory -- call it /project-static/, for instance.
Then only include this line in urls.py:
urlpatterns += staticfiles_urlpatterns()
(remove the django.views.static.serve view)
And in settings.py, use this:
STATICFILES_DIRS = (os.path.join(PROJECT_ROOT, 'project-static'),)
Then you can put files in /project-static/ directory on your filesystem, the development server will serve them out of the /static/ URL prefix, and in production, collectstatic will find them and put them into the /static/ directory where the web server can find them.

Accessing "Media" files in Django

I'd like to love Django, but this business of static and media files in development environments is driving me nuts. Please rescue me from my stupidity.
I'm on my development machine. I have folder media in the root of my project directory.
In settings.py I have: MEDIA_ROOT = '' and MEDIA_URL = '/media/'.
In urls.py I have:
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$',
'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT, }),
)
But the only way I can get media files is by referencing /media/media/ e.g.
<img src="/media/media/image.png" />.
I expect (and want)
<img src="/media/image.png" />
Can anyone tell me what is happening here, and give me a simple recipe for setting up media file handling?
Thank you very much.
#Timmy O'Mahony - thanks! epic post, and very clear. But it leaves a couple of questions:
(1) I have to use /media/ and /static/, not media/ and static/ as MEDIA_URL and and STATIC_URL - am I missing something?
(2) If collectstatic hoses /static/, where do you put site level CSS e.g. the site's CSS files? Not in /static/, evidently.
(3) I put them in a directory '_' off the project root and set STATICFILES_DIRS to point to it - and that seems to be where the development server gets its static files, despite the urlpatterns directive. If THAT is wrong, where do you put site level CSS during development, and what is the workflow around collectstatic when you modify them - do you have to edit them one place, and collect them someplace else after every edit?
Folder Setup:
Your project root should be something like:
/app1
/app2
/media
/static
/templates
urls.py
settings.py
manage.py
The media folder is supposed to hold things like images, downloads and other material that might be uploaded during normal use of the website (i.e. after development is finished)
The static folder is supposed to hold all the CSS/JS and other material that is a part of the development of the site
Settings.py:
MEDIA_ROOT is the absolute server path to the static folder mentioned above. That means it should be something like:
MEDIA_ROOT = "/User/Bob/Sites/MySite/Project_root/media/"
MEDIA_URL is the relative browser URL you should access your media files from when you are looking at the site. It should be (usually)
MEDIA_URL = "media/"
which means all material can be viewed at http://example.com/media/
Similarly, STATIC_ROOT should be something like
STATIC_ROOT = "/User/Bob/Sites/MySite/Project_root/static/"
and STATIC_URL be
STATIC_URL = "static/"
Serving the files:
Now that you have told django where these folders should be, and the correct URLs to access them, you need to serve all requests to the folders correctly.
Usually when you are in production, you want the webserver to take care of serving your static files and media files.
If you are developing though, you can just get the django development server to serve them for you.
To do this, you tell it to route all request that come in to http://example.com/media to your MEDIA_ROOT and all requests that come in to http://example.com/static to your STATIC_ROOT.
To do this, you add some URLS to URLS.py like you have:
from django.conf import settings
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT,
}),
)
Extra:
If you have multiple apps, each with their own CSS and JS files, you mightn't want to throw them into one single /static/ folder. It might be useful to put them in subfolders of the apps they belong to:
/app1/static/ # Specific static folder
/app2/static/
/media/
/static/ # Root static folder
Now, your webserver/development server is only looking for static files where you told it to look (i.e. the root static folder) so you need to collect all the files in the subfolders and copy them to the root static folder. You could do this by hand, but django provides a command to do this for you (this is the whole point of the static app)
./manage collectstatic
Why have you made the MEDIA_ROOT setting blank? It needs to be the path to your media directory. Since, as you say, your media is in a subdirectory called media, you should put that in MEDIA_ROOT.
I followed timmy procedure but I got an error that No module name django.views. When I use import django.views in my virtualenv everything works fine i.e It's not an issue with the import of library.
However, I was able to solve this problem by following this procedure in my main urls file
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
https://docs.djangoproject.com/en/dev/howto/static-files/
I had the same problem so I added these lines
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'', include('blog.urls')),
url(r'^admin/', admin.site.urls),
url(r'^cadmin/', include('cadmin.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
in urls.py in the Django project configuration directory. more information :https://overiq.com/django/1.10/handling-media-files-in-django/
In your settings.py, make sure you add
django.core.context_processors.media
in your TEMPLATE_CONTEXT_PROCESSORS.Otherwise the MEDIA_ROOT won't work when you use it in the templates.
I am using Django 1.10. And my media folder is 'uploads'
This is the configuration in my settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
MEDIA_URL = '/uploads/'
And in the template I put the name o my MEDIA_URL before de object.name instead object.url like this:
<img src="uploads/{{ imagen_identificativa.name }} " alt="{{imagen_identificativa}}">
And it works for me.
I hope this helps.
For Django version 3 I used the following:
from django.conf import settings
from django.urls import re_path
from django.views.static import serve
# ... the rest of your URLconf goes here ...
if settings.DEBUG:
urlpatterns += [
re_path(r'^media/(?P<path>.*)$', serve, {
'document_root': settings.MEDIA_ROOT,
}),
]
my settings.py
BASE_DIR = Path(__file__).resolve().parent.parent
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
STATIC_URL = '/static/'
here is a documentation link https://docs.djangoproject.com/en/3.1/ref/views/
In case you are using Django REST with some dev server don't forget to update your dev proxy settings to redirect /media to Django backend
Here is another alternative:
Set your media configs something like this inside 'settings.py':
#Set media path
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
Lets say I have a modal called person with image filed like below:
class Person(models.Model):
name = models.CharField(max_length = 30)
photo = models.ImageField(upload_to = 'photos')
Now here upload_to path we are taking about is inside the MEDIA_ROOT folder. In my case a media folder will be created inside which photos folder will be created and our media here will be dumped.
So now in my template I do something like this:
<img src="{{ person.photo.url}} />
So in short, you got a field, use it like this:
src ={{ object.field.url}}
Hope that helps! Happy Coding!