I want to display an image on my website. I've been looking through the Django documentation and the other posts on stackoverflow, but I haven't gotten this to work.
I have an image name 'under-construction.jpg'. It lives in the /home/di/mysite/myapp/static/images directory.
I have a template like this:
<img src="{{ STATIC_URL }}images/under_construction.jpg" alt="Hi!" />
in my views.py I have this:
def under_construction(request):
return render(request, 'under_construction.html')
In my settings.py, I have this:
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# Additional locations of static files
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.
'/home/di/mysite/myapp/static',
'/home/di/mysite/myapp/static/images',
)
I executed ./manage.py collectstatic and it put a lot of files in /home/di/mysite/admin and /home/di/mysite/images. What do I have to do get my image to show up?
All you need to do is edit settings.py to be as the 4 following points and create a new folder (static) in the same folder settings.py is located
in the folder static you can create another folder (images) in it you can put the (under_constructioon.jpg)
STATICFILES_DIRS = (os.path.join( os.path.dirname( __file__ ), 'static' ),)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',)
STATIC_URL = '/static/'
STATIC_ROOT = ''
after you're done with the prev. points you can write
<img src="{{ STATIC_URL }}images/under_construction.jpg" alt="Hi!" />
I have faced same problem displaying the static image. suffered a lot and spent a lot lot of time in this regard. So thought to share my settings.
settings.py
STATIC_ROOT = ''
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = '/static/admin/'
import os.path
STATICFILES_DIRS = (
"D:/temp/workspace/offeronline/media",
(os.path.join( os.path.dirname( __file__ ), 'static' )),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
urls.py
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf here ... and at the end of the file add the following line
urlpatterns += staticfiles_urlpatterns()
and finally added the following code to the template tag and it worked
<img src="{{ STATIC_URL }}images/i1.png" />
I have solved that problem like this.
STATIC_ROOT = '/path/to/project/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
)
Django will not directly get files directly even you do this. You need to link this static directory for each application of yours. Just go to the django app dir run following command..
cd /path/to/project/my_proj/my_app
ln -s /path/to/project/static/
This will work only in debug mod. You need to set DEBUG = true in settings.py file. This should work with django's development server.
Django won't serve any static file in production mod. You need to serve static files with web-server in production mod.
More information can be found here..
Django does support static files during development, You can use the django.views.static.serve() method in view to serve media files.
But using this method is inefficient and insecure for production setting.
for Production setting in Apache
https://docs.djangoproject.com/en/1.2/howto/deployment/modpython/#serving-media-files
set STATIC_ROOT = /path/to/copy/files/to
have you added
urlpatterns += patterns('django.contrib.staticfiles.views', url(r'^static/(?P<path>.*)$', 'serve'),
or you can also do this
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf here ...
urlpatterns += staticfiles_urlpatterns()
and of course try not to server static files through django it does have some overhead instead configure your http server to serve them, assuming you have an http server (nginx is quite good).
Related
I've been stuck for awhile and I can't seem to get it. Before you say python manage.py collectstatic yes, I've done that.
Here's the issue: I am using one of mezzanine's solid layout. It doesn't seem like the mezzanine's files merge with the solid template layout.
On my front page, the CSS works, but if i head over to /admin page, then the css loads like this admin/static/mezzanine/some_css.css. Anything but the root main page loads the css file. So I'm guessing it's that path, but I've double checked my root path, it seems correct?
settings.py
PROJECT_ROOT = BASE_DIR = os.path.dirname(PROJECT_APP_PATH)
# PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) also tried this
STATIC_URL ='static/'
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
# STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, "solid/static"), ) also tried this
STATICFILES_DIRS = (
os.path.join(os.path.realpath(PROJECT_ROOT), "solid/static"),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
)
urls.py
urlpatterns +=[]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
simplfied file structure
app
---app
---solid
static
admin
css
mezzanine
templates
---static
admin
css
mezzanine
manage.py
You are missing an important thing named a slash in the begining. Put a slash in front.
STATIC_URL ='/static/'
I have been breaking my head over this for a full day but can't figure out the problem. It happened after I copied my project from one machine to another.
Settings.py
STATIC_URL = '/static/'
STATIC_ROOT = 'staticfiles'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
Mentioned 'django.contrib.staticfiles' in INSTALLED_APPS as well.
Folder structure :
Django-Projects (root)
project
app
static
css
home.css
js
manage.py
Template :
{% load staticfiles %}
<link rel="stylesheet" href="{% static 'css/home.css' %}">
urls.py
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'', include('app.urls')),
)
It throws an error in the console on opening the template :
GET http://127.0.0.1:8000/static/css/home.css
Failed to load resource: the server responded with a status of 404 (NOT FOUND)
What might be wrong here ? Please help me out. Much thanks!
In your settings.py
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
STATIC_URL = '/static/'
Then in your template file:
<link rel="stylesheet" href="{{ STATIC_URL }}css/home.css">
With the directory root structure that you have shown, I think the above setting should work. Have not tested it though. Let me know if it works.
set DEBUG=True and see if it works .. this means, django will serve your static files, and not httpserver which in this case doesnt exist since you run the app locally.
I had researched this problem for a full day. This will be okay:
DEBUG = True
ALLOWED_HOSTS = []
Django default BASE_DIR will search static content for you. But in your case you changed the way before initial project. So for that in your case you have to change your BASE_DIR like this .. then only static file will serve correctly
BASE_DIR = os.path.dirname(os.path.abspath(__file__) + '../../../')
Updated:
I didn't see that comment. ! DEBUG = True only for development and You set as False so will django use STATIC_ROOT = 'staticfiles' to serve the static content on the production environment ... Thank you
You don't have to refer to STATIC_ROOT = 'staticfiles'
Just Like that:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
I had the same issue in Django.
I added to my settings: STATIC_ROOT = 'static/'
It was the only problem.
Ive checked over quite a few of the other threads on being unable to serve static content using the static file app within Django but as yet have yet to find a solution.
settings.py
STATIC_ROOT = '/opt/django/webtools/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
"/home/html/static",
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
Template
relevant line....
<img src="{{ STATIC_URL }}macmonster/img/macmonster-logo-blue.png" >
Logs
From the logs it looks like the path is correct, but alas it is still resulting in a 404..
[10/Feb/2013 16:19:50] "GET /static/macmonster/img/macmonster-logo-blue.png HTTP/1.1" 404 1817
[10/Feb/2013 16:19:51] "GET /static/macmonster/img/macmonster-logo-blue.png HTTP/1.1" 404 1817
For local serving of static files, if you haven't set up any form of collecting of staticfiles and if you're running Django 1.3+, I believe this is the way your settings.py should look like when refering to static files
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# Additional locations of static files
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.
'/Users/cupcake/Documents/Workspaces/myDjangoProject/someOtherFolderPerhapsIfYouWant/static',
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
Notice that I've left out the STATIC_ROOT here.
This is because I don't have the need for static files collection "just yet".
The collecting of static files is to allieviate(spelling) the problems with serving multiple diffrent staticfiles folders, so they merged the staticfiles app that was used normally for helping with this problem.
What this does, and it's described in the docs, is to take all the static files from all your apps and put them into one (1) folder for easier serving when putting your app into production.
So you're problem is that you've "missed" this step and that's why you're getting a 404 when trying to access them.
Therefore you need to use a absolute path to your static files ie. on a mac or unix system it should look something like this:
'/Users/cupcake/Documents/Workspaces/myDjangoProject/someOtherFolderPerhapsIfYouWant/static',
Also, you could simplify and "fix" the need of having a hardcoded path like that which I used for illustration and do like this
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATICFILES_DIRS = (
PROJECT_ROOT + '/static/'
)
This would fix the portability problem as well. A good Stackoverflow post about that is found here
I hope I made it a bit clearer, otherwise please correct me if I'm wrong ^_^!
For collecting and how to manage static files in the newer versions of Django read this link
The staticfiles app
Change
STATIC_URL = '/static/'
set
STATIC_URL = 'http://yourdomain.com/static/'
it's unbelievable but, after 1 hour searching it solution solve my problem with static files and remove STATIC_ROOT from STATICFILES_DIRS.
STATICFILES_DIRS is just for collecting all the static in modules and store it in STATIC_ROOT.
It is very strange that my django website (setup on a linux server with django 1.3) can be visit correctly with DEBUG = True. But when I changed the option to DEBUG = False the static content won't load (css files and images can not be found)
Here's related options i got in my setting.py:
DEBUG = False
STATIC_ROOT = ''
ADMIN_MEDIA_PREFIX = '/static/admin/'
STATICFILES_DIRS = ("/home/ubuntu/ls_website/static/",)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
Anybody have any idea? If the version is too low, I would wait a while for 1.5 release.
I found when debug=False, django won't load static files automatically. Options are set static path in urls.py or serve static files with apache.
People said set static path in urls.py is slower than serve static files with apache. Don't know why though...
Staticfiles doesn't do anything when DEBUG=False. You need to serve those files with apache. Staticfiles has the ability to collect the files to one spot for you to make it easy, then you use some apache magic (assuming here since you didn't specify) to have apache intercept those requests and serve the static files for you.
Alias /robots.txt /home/username/Python/project/site_media/static/robots.txt
Alias /favicon.ico /home/username/Python/project/site_media/static/favicon.ico
Alias /static/ /home/username/Python/project/site_media/static/
I don't remember if it is buildstatic, build_static, collectstatic or collect_static to copy those files from your development stop to your deployment spot, but these variables control how staticfiles does its magic
# Absolute path to the directory that holds static files like app media.
# Example: "/home/media/media.lawrence.com/apps/"
STATIC_ROOT = os.path.join(PROJECT_ROOT, "site_media", "static")
# URL that handles the static files like app media.
# Example: "http://media.lawrence.com"
STATIC_URL = "/static/"
# Additional directories which hold static files
STATICFILES_DIRS = [
os.path.join(PROJECT_ROOT, "static"),
os.path.join(PROJECT_ROOT, "media"),
]
This assumes your static files are in the static folder of your project, and you want to serve them from the site_media folder.
I also move between Windows and Linux for development. To get around the problem of absolute paths in settings.py, I use this function:
def map_path(directory_name):
return os.path.join(os.path.dirname(__file__),
'../' + directory_name).replace('\\', '/')
Which you can implement in this fashion:
STATICFILES_DIRS = (
map_path('static'),
)
This function is tailored for Django 1.4.x. You'll need to modify it slightly for Django 1.3.x. Hope that helps you out.
i'm a Django newbie working on my first project and having a problem with static files.
I have created a simple auth system using django.contrib.auth consisting of two templates: mysite/templates/index.html and mysite/templates/registration/login.html. I have global static content in mysite/static which I want to be able to access on all templates rendered by all apps.
mysite/templates/index.html contains <img src="{{ STATIC_URL }}pics03.jpg"/> which renders as "static/pics03.jpg" and loads fine when I visit the url localhost:8000/
mysite/templates/registration/login.html contains <img src="{{ STATIC_URL }}pics03.jpg"/> which also renders as "static/pics03.jpg" and does not load when I visit the url "localhost:8000/accounts/login/"
In my urls.py I have:
urlpatterns = patterns('',
url(r'^$', 'mysite.views.home'), # plays index.html template
url(r'^accounts/login/$', 'django.contrib.auth.views.login'),
In my settings.py I have:
PROJECT_DIR = os.path.dirname(__file__)
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(PROJECT_DIR,'static'),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
STATIC_URL = '/static/'
STATIC_ROOT = ''
I was under the impression that Django should be looking for global static content in STATICFILES_DIRS, but it doesn't find the static content for login.html even if I change the url in there to an absolute path to the static folder. Can anyone shed any light on this?
Your problem is that you arent listening to the URL "/static/" nowhere in your urls.py
If you serve your application via a webserver like apache or nginx then this is normal as the webserver would handle the static files itself.
For development Django comes with a built-in static server
to urls.py, at the very end add
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
What this does is to add the /static/ url and let you serve those without a webserver.
This is equivalent to
url(
regex=r'^static/(?P<path>.*)$',
view='django.views.static.serve',
kwargs={'document_root': settings.STATIC_ROOT,}
)
some people will tell you that you need to wrap the URL-rules in a "if settings.DEBUG" to use the dev-only rules, but this isnt needed at all and actually i find that to be a bad advice.
Are you having trouble when using the build in runserver or are you serving using Apache or similar? I've struggled with this a bit. The documentation I follow is: https://docs.djangoproject.com/en/stable/howto/static-files/
The second part is key when you are ready to deploy. You need to define a static root (which will be empty to begin with) and run the manage.py collectstatic command to move the static files from throughout your project into that folder. Then you can serve them from there.
Does changing STATIC_ROOT='' to STATIC_ROOT='/' help?
It seems to me the only difference is that static/pics03.jpg (relative path) exists on the home page, but doesn't on the other.
The absolute path /static/pics03.jpg exists in both cases. If changing STATIC_ROOT doesn't help, just add a / to the beginning of the urls.