Like the 1 billionth static file question about Django 1.3. I've been searching and trying so many things but nothing seems to work for me. Any help would be appreciated. Will try and give as much information as possible.
URL FILE
urlpatterns = patterns('',
url(r'^projectm/statictest/$','project_management.views.statictest'),)
VIEW
def statictest(request):
return render_to_response('statictest.html',locals())
TEMPLATE
<html><head><title>Static Load Test Page</title></head>
<body>
{% load static %}
<img src="{{ STATIC_URL }}testimage.jpg" />
</body></html>
SETTINGS
STATIC_ROOT = '/home/baz/framework/mysite/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = ('',)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
TEMPLATE_DIRS = (
"/home/baz/framework/mysite/templates"
FILES
-bash-3.2$ pwd
/home/baz/framework/mysite/templates
statictest.html
-bash-3.2$ pwd
/home/baz/framework/mysite/project_management/static
-bash-3.2$ ls
testimage.jpg
Not too sure if there is any other information that would be helpful. But basically when I go to this test page and check the page source, the url is pointing to
<img src="/static/testimage.jpg" />
However the image does not load. I have tried this on multiple browsers too. Maybe I am missing an imort statement somewhere?
cheers for the help
Are you using the built in runserver command or do you serve the Django app some other way?
If you use runserver then your problem is that you don't tell Django where to find your static assets in the filesystem. You need to set STATIC_ROOT to a filesystem path where your static assets can be found. Try setting it to: /home/baz/framework/mysite/project_management/static/
If you are using a different server (like gunicorn behind Nginx for example) then it is the responsibility of the front-end server to intercept requests for /static/ and serve them for you.
Also remember to run the ‘collectstatic’ management command once you have set ‘STATIC_ROOT’.
https://docs.djangoproject.com/en/1.4/howto/static-files/#deploying-static-files-in-a-nutshell
Related
I am trying to attach an image to my page (per https://docs.djangoproject.com/en/1.10/howto/static-files/#configuring-static-files), but it cannot be displayed: http://prntscr.com/evwern
settings.py
STATIC_URL = '/portfolio/'
urls.py
urlpatterns = [
url(r'^$', index, name='index'),]
index.html
{% load static %}
<img src="{% static '/catalog/static/portfolio/oh_i_ah.jpg' %}" alt="My image" style="width:640px;height:473px;"/>
Path to the image: mysite/portfolio/catalog/static/portfolio/oh_i_ah.jpg
If I try to open the image in the new tab it throws:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/portfolio/catalog/static/portfolio/oh_i_ah.jpg
1) You did not specify your app directory name. Need to know the app/directory name to answer your question properly.
2) You did not use 'static' properly.
3) You did not specify whether you are using default django development server or some production server. I am assuming that it's default django development server with DEBUG=True.
Solution
Let's imagine: You have an app named app0 (let's say you created that with "python manage.py startapp app0") and you have created a directory called "static " inside of that (following default django convention over configuration). Inside of this 'static' directory you have created another directory called 'app0'. So, you are going to put your file inside "/app0/static/app0". So, your file path becomes: "/app0/static/app0/oh_i_ah.jpg"
Now, set STATIC_ROOT properly in the settings.py
In the template file refer the file as {% static "app0/oh_i_ah.jpg" %} (without leading forward slash).
Now, everything will be ok.
Yes, you can put the static files outside of any app directory if you configure STATICFILES_DIRS, STATIC_ROOT in settings.py correctly.
Please properly describe your problem with as much details as possible so that we can help you in the right way.
in settings.py
import os
STATIC_URL = '/portfolio/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'), )
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
and
python manage.py collectstatic
in index.html
{% load staticfiles %}
<img src="{% static '/portfolio/oh_i_ah.jpg' %}" alt="My image" style="width:640px;height:473px;"/>
I've read django static files document and made my django static files settings like this
setting.py
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
STATIC_ROOT = os.path.join(PROJECT_PATH, 'static')
STATIC_URL = '/static/'
html page
<img src="{% static "admin/img/author.jpg" %}" alt="My image"/>
So if I address one of django default static files, it works fine. But if I add my own file and folders to the static folder, it doesn't show it.
I tried
python manage.py collectstatic
But nothing changed. How can I make it work?
A few things...
STATICFILES_DIRS = (
'path/to/files/in/development',
)
STATIC_ROOT = 'path/where/static/files/are/collected/in/production'
When DEBUG = True, Django will automatically serve files located in any directories within STATICFILES_DIRS when you use the {% static 'path/to/file' %} template tag.
When DEBUG = False, Django will not serve any files automatically, and you are expected to serve those files using Apache, Nginx, etc, from the location specified in STATIC_ROOT.
When you run $ manage.py collectstatic, Django will copy any and all files located in STATICFILES_DIRS and also files within any directory named 'static' in 3rd party apps, into the location specified by STATIC_ROOT.
I typically structure my project root as such:
my_project/
/static_assets/ (specified in STATICFILES_DIRS)
/js
/images
/static (specified in STATIC_ROOT)
I hope that helps you understand how the staticfiles app works.
STATIC_ROOT is where files are collected and moved to when collectstatic runs.
If you want files to be consolidated to there they should be found by the static file finder.
As an example, include the following in your settings
STATICFILES_FINDERS = ("django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder")
now for one of the apps that are a part of your project, create a folder called static and put something in it.
When you run collectstatic you should see that file mentioned and it copied to your STATIC_ROOT
You can try adding
STATICFILES_DIRS = (
STATIC_PATH,
)
to your settings.py.
Also, if you haven't already, make sure to include
{% load static from staticfiles %}
in each of your templates where you wish to reference static files.
Lastly, make sure that the file you are referencing actually exists and the file path to it is correct.
Try to:
<img src="{{ STATIC_URL }}admin/img/author.jpg" alt="My image"/>
And in your view must be something like this:
...
from django.shortcuts import render_to_response
from django.conf import settings
def my_view(request):
...
static_url = getattr(settings, 'STATIC_URL')
...
return render_to_response(
template_name,
RequestContext(request, {
'STATIC_URL': static_url,
}))
I've looked through countless answers and questions trying to find a single definitive guide or way to do this, but it seems that everyone has a different way. Can someone please just explain to me how to serve static files in templates?
Assuming I've just created a brand new project with Django 1.4, what all do I need to do to be able to render images? Where should I put the media and static folders?
Put your static files into <app>/static or add an absolute path to STATICFILES_DIRS
Configure your web server (you should not serve static files with Django) to serve files in STATIC_ROOT
Point STATIC_URL to the base URL the web server serves
Run ./manage.py collectstatic
Be sure to use RequestContext in your render calls and {{ STATIC_URL }} to prefix paths
Coffee and pat yourself on the back
A little bit more about running a web server in front of Django. Django is practically an application server. It has not been designed to be any good in serving static files. That is why it actively refuses to do that when DEBUG=False. Also, the Django development server should not be used for production. This means that there should be something in front of Django at all times. It may be a WSGI server such as gunicorn or a 'real' web server such as nginx or Apache.
If you are running a reverse proxy (such as nginx or Apache) you can bind /static to a path in the filesystem and the rest of the traffic to pass through to Django. That means your STATIC_URL can be a relative path. Otherwise you will need to use an absolute URL.
The created project should have a static folder. Put all resources (images, ...) in there.
Then, in your HTML template, you can reference STATIC_ROOT and add the resource path (relative to the static folder)
Here is the official documentation:
How to manage static files: https://docs.djangoproject.com/en/1.4/howto/static-files/
Static Files in general: https://docs.djangoproject.com/en/1.4/ref/contrib/staticfiles/
If you are planning to to deploy in a production type setting then you should read the section here: https://docs.djangoproject.com/en/1.4/howto/static-files/#staticfiles-production
Generally you put our static and media folders outside of the django project app
Define your STATICFILES_DIRS, STATIC, and MEDIA path in the settings.
Create staticfiles folder beside your templates folder, urls.py, settings.py, etc...
You don't have to create media folder because it will automatically created when you upload images.
In your urlconf put this one:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static
admin.autodiscover()
urlpatterns = patterns('',
.............
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
In templates:
{% load static %}
<img src="{% static 'images.png' %}">
<img src="{{MEDIA_URL}}images.png">
This should be super simple, but somehow its has had me stuck all morning. I'm developing locally, using the django debug server, and with this filestructure:
/project/ (django project)
/static/ (static files)
In the settings.py MEDIA_ROOT and MEDIA_URL are both set to '/static/' and I'm using this in my urls.py
url(r'^(?P<path>.*)$', 'django.views.static.serve', {'document_root': '../static'}),
In my templates, the files that need to be server from the static directory are configured as such:
<link rel="stylesheet" href="{{ STATIC_URL }}css/style.css">
That all works as it should - the javascript/css/images are all served properly from the hompage. However, when I go to a subdirectory, such as http://127.0.0.1:8000/news/ then all the links are broken.
I've tried using a variety of the os.import options to get it to do the relative links properly, but havent had any luck. Is there a way that I could force it to be relative to the base url, or perhaps hardcode it to my filesystem?
Any help would be amazing!
In this line in your urls.py file, the '../static' should be changed to an absolute directory. Try changing it and see what happens.
Your file:
url(r'^(?P<path>.*)$', 'django.views.static.serve', {'document_root': '../static'}),
Should look more like:
url(r'^(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/full/path/to/static'}),
To give you an example, mine is set up a little differently, but I still use a full path.
Here's how mine is setup:
in settings.py
STATIC_DOC_ROOT = '/Users/kylewpppd/Projects/Django/kl2011/assets/'
and in urls.py:
(r'^assets/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_DOC_ROOT, 'show_indexes':True}),
I'm serving my static files from 'localhost:8000/assets/'.
I just had the same problem, and I solved it by removing first slash from STATIC_URL='/static/' and making it STATIC_URL = 'static/' just like philipbe wrote above.
Wierd thing is that '/media/' works fine for MEDIA_URL at the same time (while 'media/' breaks layout).
Anyway - just change STATIC_URL to be equal to 'static/' with no leading slash, and you'll solve it.
How do your links break when you go to a subdirectory? Can you explain that further please.
Does django 1.3 support some kind of strange relative url routing for static media?
If it can be served from the homepage but not others, doesn't that sound exactly like your STATIC_URL is a relative location?
What is your STATIC_URL? It should be absolute and start with a slash.
All,
I've tried the tips found on the forum. Unfortunately i'm still stuck.
The image doesn't appear in the template.
As far as i've traced the errors now they are twofold:
1) one where the picture should appear there is still a broke link and an error message:
Failed to load resource: the server responded with a status of 404 (NOT FOUND),
**http://127.0.0.1:8000/Point3D/grafiek/laptop.jpg**
So it does go in the right path, but can't find the image.. Which is in my MEDIA_ROOT
or I receive:
Resource interpreted as image but transferred with MIME type text/html with:
**http://127.0.0.1:8000/Point3D/grafiek/**
2) The other error is that if i go to : http://127.0.0.1:8000/media/ i get:
Permission denied: /media/
maybe this has something to do with it.
For the rest i've followed roberts solution for now but without any luck..
Any help would be very much appreciated!
What's your template looking like? It's should be something like:
<img src="{{ MEDIA_URL }}Point3D/grafiek/laptop.jpg" alt="" />
I'm guessing the right path for your image should be http://127.0.0.1:8000/media/Point3D/grafiek/laptop.jpg
Are you including {{ MEDIA_ROOT }} in your tag.
Also, make sure you are calling the template with a RequestContext object, because otherwise {{ MEDIA_ROOT }} will not be set in your template. Try using django.views.generic.simple.direct_to_template rather than django.shortcuts.render_to_response. Note that direct_to_template is called just like render_to_response except it takes request as the first argument.
from django.views.generic.simple import direct_to_template
# your view code here
return direct_to_template(request, 'path/to/template.html', **kwargs)
Assuming media on your file system is at:
/home/username/django-project/media/images/favicon.ico
In your settings.py, you should have:
import os
PROJECT_PATH = os.path.dirname(__file__)
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media')
MEDIA_URL = '/media/'
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.media',
)
Your project urls.py should also contain the following which should only work in DEBUG mode:
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT.replace('\\','/')}, name='media'),
)
Your template should include media like the following:
<link rel="icon" href="{{ MEDIA_URL }}images/favicon.ico" />
Permission denied on /media/ is exactly what is supposed to happen, as otherwise every user of you page could view all the files in that directory (Would be the same as configuring Apache to allow Indexing of a Directory, which is, in allmost al cases, not what you want. Try accessing the file in your browser by pasting the complete url, (and include the media url in your path!):
http://127.0.0.1:8000/media/Point3D/grafiek/laptop.jpg
If that does not work, make sure you have Django or Apache configured to serve the static files you try to access.
edit:
And one more thing that could cause your trouble: /media/ is the default for the admin media url. If your admin media url and your media url are the same thats no good. Change that so your MEDIA_URL and your ADMIN_MEDIA_PREFIX are not the same.