When working locally on a Django project that uses static files and the default static files backend, I am running into an issue when I want to get full absolute urls to the static files instead of only the path.
My settings:
DEBUG = True
BASE_DIR = Path(__file__).resolve().parent.parent
INSTALLED_APPS = ["django.contrib.staticfiles", ...]
STATIC_ROOT = BASE_DIR / "static_root"
STATIC_URL = "/static/"
MEDIA_ROOT = BASE_DIR / "media_root"
MEDIA_URL = "/media/"
STATICFILES_DIRS = (BASE_DIR / "static",)
STATICFILES_FINDERS = (
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
)
Everything works, the admin's CSS is loaded, images work, etc. But when I get the path of a file with this code:
from django.contrib.staticfiles.storage import staticfiles_storage
static_path = staticfiles_storage.url("path_to_folder/some_file.jpg")
That result is a relative path: /static/path_to_folder/some_file.jpg. This is a problem when these urls are used from my external frontend: it now has to prepend the backend's base url to all static assets. But if I'd want to deploy the static assets to S3 for example, in production, then I should not prepend these paths with the domain of the backend.
So what I tried to do was to change the STATIC_URL setting to http://localhost:8000/static/. That way the full url is passed to the frontend, but I could really easily change this setting in the backend in production.
And this is where the problem rears its head: when I change STATIC_URL to http://localhost:8000/static/, none of my static files work anymore, I just get a 404. The admin page also is completely unstyled because of this.
So, to make a long story short: how can I use an absolute STATIC_URL in local development mode with DEBUG=True?
I have created a reproduction repro: https://github.com/kevinrenskers/django-problem-repro.
Found the solution here: https://docs.djangoproject.com/en/4.1/ref/contrib/staticfiles/#django.contrib.staticfiles.views.serve.
Simply add this to the end of urls.py:
from django.conf import settings
from django.contrib.staticfiles import views
from django.urls import re_path
if settings.DEBUG:
urlpatterns += [
re_path(r'^static/(?P<path>.*)$', views.serve),
]
Then the static files will work again even with an absolute URL as the STATIC_URL setting.
In the result (real server) the css, js and images are not connected, but the thing is that in localhost it works perfect. I dont know what any other details do you need so write comment and I will edit this queston :)
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
PROJECT_ROOT = os.path.dirname(__file__)
STATIC_URL = '/static/'
STATIC_DIR = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [STATIC_DIR]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
CRISPY_TEMPLATE_PACK = 'uni_form'
LOGIN_URL = ''
Most probably you misconfigured nginx file or did not mention in nginx file.
You need to write path in nginx file something like below:
location static_url {
alias static_dir
}
After update to Django 1.10 I have a problem with static file images. Now Django add to static file path "media" link... For example before it was "/static/images/avatar.jpeg" now "/media/static/images/avatar.jpeg"
Admin
Settings
STATIC_URL = '/static/'
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(BASE_DIR, 'static'),
'static',
)
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
Just upgraded to Django 1.4, and having serious trouble with the new 'improved' serving of static and media files on development server. I love Django, but why on earth they have made serving these files doubly more complicated with STATIC_URL,STATIC_ROOT, STATICFILES_DIR now is utterly beyond me.
I'm simply trying to serve all files, static and uploaded, on the development server. I have the STATIC_URL files working, after much experimentation, but I simply cannot get the MEDIA_URL files to be served as well.
Settings:
DIRNAME = os.path.dirname(__file__)
MEDIA_ROOT = os.path.join(DIRNAME, 'media/')
MEDIA_URL = '/media/'
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = ()
I've got the media and static context processors added:
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
'django.core.context_processors.media',
'django.core.context_processors.static',
"django.core.context_processors.request",
'satchmo_store.shop.context_processors.settings',
'django.contrib.messages.context_processors.messages',
)
and I've added in the url confs:
# serve static and uploaded files in DEV
urlpatterns += staticfiles_urlpatterns()
urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
with the two conf settings added as indicated in the docs, first one for static, second for media.
my structure, website being an app and static dir placed inside it as instructed on djangoproject:
<myproject>
--media
--settings
--templates
--website
|->static
In templates I can serve static content no problem with
{{STATIC_URL}}css/style.css
But any uploaded image, this one using photologue, is not served, but the urls are correct:
/media/photologue/photos/cache/spawning-2_admin_thumbnail.jpg
That directory structure does exit under media/
Super, super confused. It all seems so ridiculously complicated now, whereas I never had any issues before.
I´m very new to Django and I´ve never had any problem with static content.
This is my configuration. I hope it can help
My folder structure
django-project
--mainapp
----settings.py
----wsgi.py
----[...]
--otherapp
--fixtures
--static
--templates
--manage.py
--requirements.txt
settings.py
import os, socket
DEBUG = True
TEMPLATE_DEBUG = DEBUG
MAIN_APP = os.path.abspath(os.path.dirname(__file__))
PROJECT_ROOT = os.path.abspath(os.path.join(MAIN_APP, ".."))
MY_LOCALHOST = "VirusVault.local" # this is the real name of my local machine :)
try: HOST_NAME = socket.gethostname()
except: HOST_NAME = "localhost"
[...]
if HOST_NAME == MY_LOCALHOST:
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static/')
STATIC_URL = "/static/"
MEDIA_ROOT = os.path.join(STATIC_ROOT, 'media/')
MEDIA_URL = "/media/"
else:
STATIC_ROOT = "/server/path/to/static/files"
STATIC_URL = "http://server.com/static/"
MEDIA_ROOT = "/server/path/to/static/files/media/"
MEDIA_URL = 'http://server.com/static/media/'
You need to add 'django.contrib.staticfiles' to INSTALLED_APPS
urls.py
if settings.HOST_NAME == settings.MY_LOCALHOST:
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
)
urlpatterns += patterns('',
(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_ROOT, 'show_indexes': True}),
)
If you are using Django 1.4 folder structure, you've moved settings.py to your new website app folder which means your MEDIA_ROOT is now incorrect. Not sure if a relative location works in this case, but it should be something like this
MEDIA_ROOT = os.path.join(DIRNAME, '../media/')
It might be simpler to use an absolute path.
I intended to write a comment first but somehow add comment button doesn't work.
Did you check the permissions of media directory?
Since it became an answer, I am going to dump one of my perfectly working Django 1.4 sites configuration.
structure:
-myproject
-- media
-- static
-- templates
-- myproject
--- settings.py
--- urls.py
settings.py:
PROJECT_ROOT = os.path.dirname(os.path.dirname(__file__)) # Not the best way but works
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media/')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static/')
STATIC_URL = '/static/'
urls.py:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = patterns('',
...
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
)
urlpatterns += staticfiles_urlpatterns()
So I updated my project settings with the following scheme
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
/settings
base.py
prod.py
dev.py
Is this the correct STATICFILES_DIRS settings for the above configuration?
STATICFILES_DIRS = [
os.path.join(PROJECT_ROOT, "site_media", "static"),
]
STATIC_URL = "/site_media/static/"
The templates render just fine using
TEMPLATE_DIRS = [
os.path.join(PROJECT_ROOT, "templates"),
]
So I'm a little turned around as to why my css files arent working
Home.html
<link rel="stylesheet" href="{{ STATIC_URL }}css/home.css" />
You might want to change your PROJECT_ROOT to something like this:
# cwd is settings. determine project path
cwd = os.path.dirname(os.path.abspath(__file__))
PROJECT_ROOT = cwd[:-9] # chop off "settings/"
That should get your project root where you want it. Also, what link is being created on the front end when you try to use {{STATIC_URL}}?
You might want to check out this link for more information on splitting up the settings.py file.