Django static files won't load - python

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.

Related

Sending Email with Image inside the body of the html - Django [duplicate]

I'm new to Django and I'm trying to learn it through a simple project I'm developing called 'dubliners' and an app called 'book'. The directory structure is like this:
dubliners/book/ [includes models.py, views.py, etc.]
dubliners/templates/book/
I have a JPG file that needs to be displayed in the header of each Web page. Where should I store the file? Which path should I use for the tag to display it using a template? I've tried various locations and paths, but nothing is working so far.
...
Thanks for the answer posted below. However, I've tried both relative and absolute paths to the image, and I still get a broken image icon displayed in the Web page. For example, if I have an image in my home directory and use this tag in my template:
<img src="/home/tony/london.jpg" />
The image doesn't display. If I save the Web page as a static HTML file, however, the images display, so the path is correct. Maybe the default Web server that comes with Django will display images only if they're on a particular path?
Try this,
settings.py
# typically, os.path.join(os.path.dirname(__file__), 'media')
MEDIA_ROOT = '<your_path>/media'
MEDIA_URL = '/media/'
urls.py
urlpatterns = patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
)
.html
<img src="{{ MEDIA_URL }}<sub-dir-under-media-if-any>/<image-name.ext>" />
Caveat
Beware! using Context() will yield you an empty value for {{MEDIA_URL}}. You must use RequestContext(), instead.
I hope, this will help.
In production, you'll just have the HTML generated from your template pointing to wherever the host has media files stored. So your template will just have for example
<img src="../media/foo.png">
And then you'll just make sure that directory is there with the relevant file(s).
during development is a different issue. The django docs explain it succinctly and clearly enough that it's more effective to link there and type it up here, but basically you'll define a view for site media with a hardcoded path to location on disk.
Right here.
I do understand, that your question was about files stored in MEDIA_ROOT, but sometimes it can be possible to store content in static, when you are not planning to create content of that type anymore.
May be this is a rare case, but anyway - if you have a huge amount of "pictures of the day" for your site - and all these files are on your hard drive?
In that case I see no contra to store such a content in STATIC.
And all becomes really simple:
static
To link to static files that are saved in STATIC_ROOT Django
ships with a static template tag. You can use this regardless if
you're using RequestContext or not.
{% load static %} <img src="{% static "images/hi.jpg" %}" alt="Hi!" />
copied from Official django 1.4 documentation / Built-in template tags and filters
In development
In your app folder create folder name 'static' and save your picture in that folder.
To use picture use:
<html>
<head>
{% load staticfiles %} <!-- Prepare django to load static files -->
</head>
<body>
<img src={% static "image.jpg" %}>
</body>
</html>
In production:
Everything same like in development, just add couple more parameters for Django:
add in settings.py STATIC_ROOT = os.path.join(BASE_DIR, "static/")(this will prepare folder where static files from all apps will be stored)
be sure your app is in INSTALLED_APPS = ['myapp',]
in terminall run command python manage.py collectstatic (this will make copy of static files from all apps included in INSTALLED_APPS to global static folder - STATIC_ROOT folder )
Thats all what Django need, after this you need to make some web server side setup to make premissions for use static folder. E.g. in apache2 in configuration file httpd.conf (for windows) or sites-enabled/000-default.conf. (under site virtual host part for linux) add:
Alias \static "path_to_your_project\static"
Require all granted
And that's all
I have spent two solid days working on this so I just thought I'd share my solution as well. As of 26/11/10 the current branch is 1.2.X so that means you'll have to have the following in you settings.py:
MEDIA_ROOT = "<path_to_files>" (i.e. /home/project/django/app/templates/static)
MEDIA_URL = "http://localhost:8000/static/"
*(remember that MEDIA_ROOT is where the files are and MEDIA_URL is a constant that you use in your templates.)*
Then in you url.py place the following:
import settings
# stuff
(r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),
Then in your html you can use:
<img src="{{ MEDIA_URL }}foo.jpg">
The way django works (as far as I can figure is:
In the html file it replaces MEDIA_URL with the MEDIA_URL path found in setting.py
It looks in url.py to find any matches for the MEDIA_URL and then if it finds a match (like r'^static/(?P.)$'* relates to http://localhost:8000/static/) it searches for the file in the MEDIA_ROOT and then loads it
/media directory under project root
Settings.py
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
urls.py
urlpatterns += patterns('django.views.static',(r'^media/(?P<path>.*)','serve',{'document_root':settings.MEDIA_ROOT}), )
template
<img src="{{MEDIA_URL}}/image.png" >
If your file is a model field within a model, you can also use ".url" in your template tag to get the image.
For example.
If this is your model:
class Foo(models.Model):
foo = models.TextField()
bar = models.FileField(upload_to="foo-pictures", blank = True)
Pass the model in context in your views.
return render (request, "whatever.html", {'foo':Foo.objects.get(pk = 1)})
In your template you could have:
<img src = "{{foo.bar.url}}">
Your
<img src="/home/tony/london.jpg" />
will work for a HTML file read from disk, as it will assume the URL is file:///home/.... For a file served from a webserver though, the URL will become something like: http://www.yourdomain.com/home/tony/london.jpg, which can be an invalid URL and not what you really mean.
For about how to serve and where to place your static files, check out this document. Basicly, if you're using django's development server, you want to show him the place where your media files live, then make your urls.py serve those files (for example, by using some /static/ url prefix).
Will require you to put something like this in your urls.py:
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '/path/to/media'}),
In production environment you want to skip this and make your http server (apache, lighttpd, etc) serve static files.
Another way to do it:
MEDIA_ROOT = '/home/USER/Projects/REPO/src/PROJECT/APP/static/media/'
MEDIA_URL = '/static/media/'
This would require you to move your media folder to a sub directory of a static folder.
Then in your template you can use:
<img class="scale-with-grid" src="{{object.photo.url}}"/>
I tried various method it didn't work.But this worked.Hope it will work for you as well. The file/directory must be at this locations:
projec/your_app/templates
project/your_app/static
settings.py
import os
PROJECT_DIR = os.path.realpath(os.path.dirname(_____file_____))
STATIC_ROOT = '/your_path/static/'
example:
STATIC_ROOT = '/home/project_name/your_app/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS =(
PROJECT_DIR+'/static',
##//don.t forget comma
)
TEMPLATE_DIRS = (
PROJECT_DIR+'/templates/',
)
proj/app/templates/filename.html
inside body
{% load staticfiles %}
//for image
img src="{% static "fb.png" %}" alt="image here"
//note that fb.png is at /home/project/app/static/fb.png
If fb.png was inside /home/project/app/static/image/fb.png then
img src="{% static "images/fb.png" %}" alt="image here"
I've had the hardest time figuring this out so I am making this post to explain as clearly as i can, what worked for me, to help someone else.
Let's say you have a project called project_name. and an app called app_name. your root directory should look like this:
/app_name
/project_name
manage.py
DEVELOPMENT.
while in development mode, your CSS and JS files should be inside ./app_name/static/app_name/..
however your images should be inside ./app_name/static/media/..
now add these to settings.py :
If this not already there, add
STATIC_URL = '/static/'
This tells Django where to find all the static files.
MEDIA_URL = '/media/'
This points Django to the folder where your images are, after it loads static. In this case it is /media/ because our images are in /static/media.
next, you should put this in the individual template where you need the image (I thought putting a single {% load static %} in the general layout.html template would suffice, it didn't):
{% load static %}
<img src="{% static image_name %}>
depending on how you set up your project, image_name could be the exact name of the image file like "image.jpg", a variable for an image field like user.image etc
lastly, go into the project_name urls.py (same folder as settings.py) and add this line to the end:
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)
basically telling Django to use a work around so you can see use the images in development.
That is all. your project will now display images while you are writing and testing your code(development)
PRODUCTION.
When you want to deploy your project, there are some extra steps you need to take.
Because Django does not serve images as static files during production, you have to install a Middleware called Whitenoise.
http://whitenoise.evans.io/en/stable/#installation
pip install whitenoise
Then add the following to settings.py:
look for MIDDLEWARE and add just under django.middleware.security.SecrutiyMiddleware:
'whitenoise.middleware.WhiteNoiseMiddleware',
Next we have to define our paths, this is because in production Django will basically collect all the static files from all our apps and rearrange them in a single folder.
Add the following to settings.py:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
This tells Django where to put static files when it collects them. In this case we are telling Django to put the files in the root folder. so after collectstatic runs our app would look like
/app_name
/project_name
/static
manage.py
Then add:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
This tells django where to put files that a user who on our site uploads..
Next,we want to go up and change Debug to False.
Debug = False
Debug mode is used for testing in development, and in production you don't want your app displaying error codes and the names of files and lines where something went wrong. potential security threat. Once you turn debug mode to false, Django changes how it serves the static files. so ordinarily, if you were to run your app now, you won't see the images..
with these done, now you are ready for production. to test that everything is okay, you can run:
python manage.py collectstatic
(type yes if prompted)
Django will collect all the static files and arrange them as necessary. if you run your project now, with debug still turned off you should see your images. you can even now delete the individual static folders in app_name or any other apps you have, if you want because Django will not use them in production. Once debug is off, Django only uses static from the collected static folder.
You can now deploy your project
If you give the address of online image in your django project it will work.
that is working for me. You should take a shot.
Also check that the problem may not be due to path, but file name or extension. While failing to dislay an image added to base.html template, the error was found related to image file extension. If you are storing the image in jpeg format, use .jpg as the extension in the img tag
<img src="{% static 'logo.jpg' %}" alt="Logo">.
Just give a try copying static folder from base path to public_html folder.
cp -r static/ ~/public_html/

Django: Static Image won't load

I have been following the official documentation to the letter, trying some of the advice for related questions on here, and just searching the web in general and I am still having no luck getting one little image to load.
I have an image called 'logo.png' and my project hierarchy looks like this:
project/
mysite/
app/
__init__.py
admin.py
models.py
urls.py
view.py
mysite/
__init__.py
settings.py
urls.py
views.py
wsgi.py
static/
logo.png
templates/
index.html
calling_image.html
Inside settings.py I have STATIC_URL = '/static/'
Inside calling_image.html I have <img src="/static/logo.png">
My template calling_image.html is called by project/mysite/app/views.py which is of course then called on by project/mysite/app/urls.py and I even tried including the following two lines (as I saw suggested a few times) at the end of my urls.py:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
Nothing works, so what have I done wrong?
Edit: Sorry I made a type, I have STATIC_URL = '/static/' with the closing slash in my settings.py and for clarification, I am running this on my dev build with python manage.py runserver
Solved: So I ended up solving this myself. I created a directory resources within project/mysite/ and placed logo.png in there. I then set STATICFILES_DIRS = (os.path.join(BASE_DIR, "resources"),) and ran collecstatic and everything worked! Didn't need to use urlpatterns += staticfiles_urlpatterns() and whatnot.
It looks like you probably need the variable STATICFILES_DIRS defined in your settings.py and that should include the location of that static directory holding logo.png.
Django only looks for static files inside a static directory inside each app by default. If you have a static file outside of any app, it won't be picked up by collectstatic automatically.
See https://docs.djangoproject.com/en/1.8/ref/settings/#std:setting-STATICFILES_DIRS
Confusion Surrounding Staticfiles
There's always a lot of confusion around Django and Static files. I believe this confusion comes from the fact that it doesn't make any sense for Django to handle static files in production, but it seems natural to use it when learning to use Django and thus when initially developing.
The reason it doesn't make any sense for Django to serve static files is that Django is a framework for rendering dynamic responses. "Static" files are not dynamic: they don't change. Thus, it's a huge waste of resources to spin up a Python application, which calls all of the Django machinery, just to find and return a file that has no dynamic content.
Staticfiles: the job of the webserver
There is something that is really good at serving static files: webservers themselves (such as a Apache, nginx, etc.). That's what they were designed to do. The webserver can run a Python/Django application or it can just locate a file and send it back, so you typically configure a webserver by telling it something like the following (in pseudo-server-speak):
When someone accesses the path /static/ let them access the files in
the following directory: /var/www/static/.
When someone accesses the
path /, spin up this Python application that lives over here:
/var/www/django-app.
Django Static Files Tools
As a result, Django comes with some helper tools that manage static files, so that your actual server can serve them.
These tools are the following(defined in settings.py):
STATIC_URL: the URL path where your server will be serving your
static files. This is just so that when you use the static templatetag, that Django knows how to urlreverse it. In other words, it's merely a convenient way of turning {% static "..." %} into /static/....
STATIC_ROOT: the place on your server (or in the
cloud somewhere), to which Django will copy your static files, so
that your server can serve them. This copying happens when you run
collectstatic.
STATICFILES_DIRS: any extra directories Django
should look for static files whenever you run collectstatic. By
default Django only looks in each app's directory for a static
directory (just like with templates).
Static Files In Development
Okay, but that's not so helpful in development where you are probably using Django's runserver command. You don't have a server running that will server static files.
Thus, you can ask Django to please also server static files for you in just this one case, because you are developing your application and don't want to run a separate server.
There is a view that automatically should pick up and serve static files when DEBUG=True. Alternately, this is also why someone might use the following:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS.
In your settings file, define STATIC_URL, for example:
STATIC_URL = 'static/'
Hopes you stored images in folder projectname/static/appname/images/image.png
Finally in your html simply add the following
<img src="appname/images/image.png" alt="My image"/>
please refer django dcumentation
I tried everything, nothing worked. In the end it turn out that image was corrupt because I opened it as bytes in Visual Code editor.
Uploaded new image and everything worked.
If I recall, you need to specify STATIC_ROOT = 'static' in settings.py and you need to have a URL to direct /static to your static files. like so.
urlpatterns += patterns('',
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT, 'show_indexes': True
}),
)
This could be a bit outdated but still works for me.
Also, are you trying to get this to work on your dev site with python manage.py runserver or on a production site?
Update
Here is an example for you main urls.py file.
from django.conf.urls import patterns, include, url
urlpatterns = (
url(r'^admin/', include(admin.site.urls)),
# more urls...
)
#The following enable structural 'static' files while in development mode.
if settings.DEBUG:
urlpatterns += patterns('',
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT, 'show_indexes': True
}),
)
patterns is imported near the top of your urls.py file.
This is where STATIC_ROOT comes in to play.
You may also need to run python manage.py collectstatic in order for your static files to be collected from your various apps and copied into the folder that is STATIC_ROOT.
See this answer for a much more in depth explanation :)

Get the path of "static" folder in django automatically

I am developing Django (1.6) app. In my app I have to use the static images to be displayed on the HTML pages (like magnifying glass for search box,logo,etc). After little bit of research I came to know that we have to create a folder (say "static") which holds the static images and then I have mention the path in my settings.py like shown below :
`STATIC_URL = '/static/'
STATICFILES_DIRS = (
"C:/Users/Welcome/Desktop/business/static/polls",
"C:/Users/Welcome/Desktop/business/static",
)`
I also added the code shown below in urls.py too after which I could get the images on my HTML pages.
urlpatterns = patterns(''......... ...........) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
My question now is every time I change the directory (current working directory or if I transfer the project to another pc ) I have to update the path in settings.py.
How to not do that ? how to get path of "static" folder automatically when I run my project. Please do help. What I'm missing ?
Normally the static files finder of django will expect that your app itself has a static sub-directory, and you can store everything there.
+ myproj
- manage.py
+ app
- __init__.py
- settings.py
- urls.py
+ static <-- notice the static directory.
+ templates
This is good of course for development where the Django server is the one serving these static files. In production you'll need to collect everything to the location declared in your STATIC_ROOT setting with the collectstatic management command.
This way you won't need to change the location each time you copy your project to a new location or a new computer.
Of course, that once you do that you can drop the STATICFILES_DIRS definition from your settings.py. This setting is used to tell Django that there are other static assets that reside outside of a certain app. If you want to use it anyway then you can define those directories relative to the project itself, i.e.:
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static")
)
Your urls.py should then use the staticfiles_urlpatterns like this:
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
For more information see the Django documentation on static files:
https://docs.djangoproject.com/en/1.7/howto/static-files/
I just figured out the solution for my question. First you need to get the current working directory and then for looking out for the folder in that current working directory(where your project is being installed) assign this to variable say path_for_images and then pass it to the STATICFILES_DIR as shown below:
path_for_images = os.getcwd()+"\static"
STATICFILES_DIRS = ( path_for images,) <-- note ,(comma) after `path_for_images`
No need to do any changes for the urls.py and images get loaded. This isn't exact pythonic way but it's surely one of the way.

Inserting Images into Django Template

I understand that there are many existing questions about Django template images, but I just can't seem to get mine to work. I currently have an app within my project and have a static folder structure that looks like
djangoproject/appname/static/images/
In the templates folder of the same django app, I have a variety of HTML files that need to reference the images in the folder shown above. In my settings.py folder, I have
STATIC_ROOT=''
STATIC_URL = 'appname/static/'
STATICFILES_DIRS = (
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
)
In my template file, I have
<img id="btnTransaction" src="{{ STATIC_URL }}images/btnTransaction.png"/>
When I run the dev server, it keeps looking at appname/images/btnTransaction.png for the image.
How can I fix this?
Get rid of appname and change to STATIC_URL= '/static/'
In the STATIC_FILES_DIR tuple, you need to have a string that is the absolute path to the static directory on your machine. So if you're *nix it would be '/User/path/to/django/static/dir/' or 'C:/path/to/django/static/dir/' if you're on Windows.
STATIC_URL, like you see here, is whatever will be output in the HTML and is meant for the absolute path of an image relative to the browser. You could do 'http://127.0.0.1:8000/static/' if you're running locally or something like 'http://mydomain.com/static/' if in production or something like 'http://static.mydomain.com/static/' if you have a CDN or just '/static/' to work for all (if you're using the same host for your static files and app).
you want the path to the images to be in a web accessible location, something away from django and your app (unless you're adding access controls, then you'll need a separate function in your views to handle that). Thing is, the img tag's src is not pulling the image in when the template is rendered server side, but in the client and the client makes a separate request for the image. If the image can't be found by the url, then it won't get shown.
Instead of using "static" use "media"
like so
settings.py
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = '/Users/YOUR USERNAME/djcode/blankpage/media/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'
and in urls.py
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
in your template reference your file like this
href="/media/styles/profile.css"

How do I include image files in Django templates?

I'm new to Django and I'm trying to learn it through a simple project I'm developing called 'dubliners' and an app called 'book'. The directory structure is like this:
dubliners/book/ [includes models.py, views.py, etc.]
dubliners/templates/book/
I have a JPG file that needs to be displayed in the header of each Web page. Where should I store the file? Which path should I use for the tag to display it using a template? I've tried various locations and paths, but nothing is working so far.
...
Thanks for the answer posted below. However, I've tried both relative and absolute paths to the image, and I still get a broken image icon displayed in the Web page. For example, if I have an image in my home directory and use this tag in my template:
<img src="/home/tony/london.jpg" />
The image doesn't display. If I save the Web page as a static HTML file, however, the images display, so the path is correct. Maybe the default Web server that comes with Django will display images only if they're on a particular path?
Try this,
settings.py
# typically, os.path.join(os.path.dirname(__file__), 'media')
MEDIA_ROOT = '<your_path>/media'
MEDIA_URL = '/media/'
urls.py
urlpatterns = patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
)
.html
<img src="{{ MEDIA_URL }}<sub-dir-under-media-if-any>/<image-name.ext>" />
Caveat
Beware! using Context() will yield you an empty value for {{MEDIA_URL}}. You must use RequestContext(), instead.
I hope, this will help.
In production, you'll just have the HTML generated from your template pointing to wherever the host has media files stored. So your template will just have for example
<img src="../media/foo.png">
And then you'll just make sure that directory is there with the relevant file(s).
during development is a different issue. The django docs explain it succinctly and clearly enough that it's more effective to link there and type it up here, but basically you'll define a view for site media with a hardcoded path to location on disk.
Right here.
I do understand, that your question was about files stored in MEDIA_ROOT, but sometimes it can be possible to store content in static, when you are not planning to create content of that type anymore.
May be this is a rare case, but anyway - if you have a huge amount of "pictures of the day" for your site - and all these files are on your hard drive?
In that case I see no contra to store such a content in STATIC.
And all becomes really simple:
static
To link to static files that are saved in STATIC_ROOT Django
ships with a static template tag. You can use this regardless if
you're using RequestContext or not.
{% load static %} <img src="{% static "images/hi.jpg" %}" alt="Hi!" />
copied from Official django 1.4 documentation / Built-in template tags and filters
In development
In your app folder create folder name 'static' and save your picture in that folder.
To use picture use:
<html>
<head>
{% load staticfiles %} <!-- Prepare django to load static files -->
</head>
<body>
<img src={% static "image.jpg" %}>
</body>
</html>
In production:
Everything same like in development, just add couple more parameters for Django:
add in settings.py STATIC_ROOT = os.path.join(BASE_DIR, "static/")(this will prepare folder where static files from all apps will be stored)
be sure your app is in INSTALLED_APPS = ['myapp',]
in terminall run command python manage.py collectstatic (this will make copy of static files from all apps included in INSTALLED_APPS to global static folder - STATIC_ROOT folder )
Thats all what Django need, after this you need to make some web server side setup to make premissions for use static folder. E.g. in apache2 in configuration file httpd.conf (for windows) or sites-enabled/000-default.conf. (under site virtual host part for linux) add:
Alias \static "path_to_your_project\static"
Require all granted
And that's all
I have spent two solid days working on this so I just thought I'd share my solution as well. As of 26/11/10 the current branch is 1.2.X so that means you'll have to have the following in you settings.py:
MEDIA_ROOT = "<path_to_files>" (i.e. /home/project/django/app/templates/static)
MEDIA_URL = "http://localhost:8000/static/"
*(remember that MEDIA_ROOT is where the files are and MEDIA_URL is a constant that you use in your templates.)*
Then in you url.py place the following:
import settings
# stuff
(r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),
Then in your html you can use:
<img src="{{ MEDIA_URL }}foo.jpg">
The way django works (as far as I can figure is:
In the html file it replaces MEDIA_URL with the MEDIA_URL path found in setting.py
It looks in url.py to find any matches for the MEDIA_URL and then if it finds a match (like r'^static/(?P.)$'* relates to http://localhost:8000/static/) it searches for the file in the MEDIA_ROOT and then loads it
/media directory under project root
Settings.py
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
urls.py
urlpatterns += patterns('django.views.static',(r'^media/(?P<path>.*)','serve',{'document_root':settings.MEDIA_ROOT}), )
template
<img src="{{MEDIA_URL}}/image.png" >
If your file is a model field within a model, you can also use ".url" in your template tag to get the image.
For example.
If this is your model:
class Foo(models.Model):
foo = models.TextField()
bar = models.FileField(upload_to="foo-pictures", blank = True)
Pass the model in context in your views.
return render (request, "whatever.html", {'foo':Foo.objects.get(pk = 1)})
In your template you could have:
<img src = "{{foo.bar.url}}">
Your
<img src="/home/tony/london.jpg" />
will work for a HTML file read from disk, as it will assume the URL is file:///home/.... For a file served from a webserver though, the URL will become something like: http://www.yourdomain.com/home/tony/london.jpg, which can be an invalid URL and not what you really mean.
For about how to serve and where to place your static files, check out this document. Basicly, if you're using django's development server, you want to show him the place where your media files live, then make your urls.py serve those files (for example, by using some /static/ url prefix).
Will require you to put something like this in your urls.py:
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '/path/to/media'}),
In production environment you want to skip this and make your http server (apache, lighttpd, etc) serve static files.
Another way to do it:
MEDIA_ROOT = '/home/USER/Projects/REPO/src/PROJECT/APP/static/media/'
MEDIA_URL = '/static/media/'
This would require you to move your media folder to a sub directory of a static folder.
Then in your template you can use:
<img class="scale-with-grid" src="{{object.photo.url}}"/>
I tried various method it didn't work.But this worked.Hope it will work for you as well. The file/directory must be at this locations:
projec/your_app/templates
project/your_app/static
settings.py
import os
PROJECT_DIR = os.path.realpath(os.path.dirname(_____file_____))
STATIC_ROOT = '/your_path/static/'
example:
STATIC_ROOT = '/home/project_name/your_app/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS =(
PROJECT_DIR+'/static',
##//don.t forget comma
)
TEMPLATE_DIRS = (
PROJECT_DIR+'/templates/',
)
proj/app/templates/filename.html
inside body
{% load staticfiles %}
//for image
img src="{% static "fb.png" %}" alt="image here"
//note that fb.png is at /home/project/app/static/fb.png
If fb.png was inside /home/project/app/static/image/fb.png then
img src="{% static "images/fb.png" %}" alt="image here"
I've had the hardest time figuring this out so I am making this post to explain as clearly as i can, what worked for me, to help someone else.
Let's say you have a project called project_name. and an app called app_name. your root directory should look like this:
/app_name
/project_name
manage.py
DEVELOPMENT.
while in development mode, your CSS and JS files should be inside ./app_name/static/app_name/..
however your images should be inside ./app_name/static/media/..
now add these to settings.py :
If this not already there, add
STATIC_URL = '/static/'
This tells Django where to find all the static files.
MEDIA_URL = '/media/'
This points Django to the folder where your images are, after it loads static. In this case it is /media/ because our images are in /static/media.
next, you should put this in the individual template where you need the image (I thought putting a single {% load static %} in the general layout.html template would suffice, it didn't):
{% load static %}
<img src="{% static image_name %}>
depending on how you set up your project, image_name could be the exact name of the image file like "image.jpg", a variable for an image field like user.image etc
lastly, go into the project_name urls.py (same folder as settings.py) and add this line to the end:
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)
basically telling Django to use a work around so you can see use the images in development.
That is all. your project will now display images while you are writing and testing your code(development)
PRODUCTION.
When you want to deploy your project, there are some extra steps you need to take.
Because Django does not serve images as static files during production, you have to install a Middleware called Whitenoise.
http://whitenoise.evans.io/en/stable/#installation
pip install whitenoise
Then add the following to settings.py:
look for MIDDLEWARE and add just under django.middleware.security.SecrutiyMiddleware:
'whitenoise.middleware.WhiteNoiseMiddleware',
Next we have to define our paths, this is because in production Django will basically collect all the static files from all our apps and rearrange them in a single folder.
Add the following to settings.py:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
This tells Django where to put static files when it collects them. In this case we are telling Django to put the files in the root folder. so after collectstatic runs our app would look like
/app_name
/project_name
/static
manage.py
Then add:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
This tells django where to put files that a user who on our site uploads..
Next,we want to go up and change Debug to False.
Debug = False
Debug mode is used for testing in development, and in production you don't want your app displaying error codes and the names of files and lines where something went wrong. potential security threat. Once you turn debug mode to false, Django changes how it serves the static files. so ordinarily, if you were to run your app now, you won't see the images..
with these done, now you are ready for production. to test that everything is okay, you can run:
python manage.py collectstatic
(type yes if prompted)
Django will collect all the static files and arrange them as necessary. if you run your project now, with debug still turned off you should see your images. you can even now delete the individual static folders in app_name or any other apps you have, if you want because Django will not use them in production. Once debug is off, Django only uses static from the collected static folder.
You can now deploy your project
If you give the address of online image in your django project it will work.
that is working for me. You should take a shot.
Also check that the problem may not be due to path, but file name or extension. While failing to dislay an image added to base.html template, the error was found related to image file extension. If you are storing the image in jpeg format, use .jpg as the extension in the img tag
<img src="{% static 'logo.jpg' %}" alt="Logo">.
Just give a try copying static folder from base path to public_html folder.
cp -r static/ ~/public_html/

Categories

Resources