Django: Serving admin media files - python

I am trying to serve static files from another domain (sub domain of current domain).
To serve all media files I used this settings:
MEDIA_URL =
'http://media.bud-inform.co.ua/'
So when in template I used
{{ MEDIA_URL }}
it was replace with the setting above. Now I am trying to serve admin media files from the same subdomain, I changed the settings this way:
ADMIN_MEDIA_PREFIX =
'http://media.bud-inform.co.ua/admin_media/',
and expected that all calls to media from my admin site will be made to this url.... But actually it didn't work this way, I still see paths to CSS made as following:
http://bud-inform.co.ua/media/css/login.css
Could you suggest how to serve admin media files correctly

MEDIA_URL and ADMIN_MEDIA_PREFIX are two different things. One is the location of your media files, while the other is the location of the django admin system's media files.
You have to make sure that the ADMIN_MEDIA_PREFIX points to somewhere where you're actually serving the admin media. Django doesn't handle that step for you.
The django admin media is at django/contrib/admin/media/. Copy or symlink that directory somewhere publicly visible and set ADMIN_MEDIA_PREFIX to reflect where you put it.

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/

dealing with static files in Django

Currently I have my settings.py regarding static files set up like so
STATIC_ROOT = ''
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
STATICFILES_DIR = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_URL = '/static/'
From reading the documentation and various blogs my understanding is that STATIC_ROOT is where the static files go. It is the absolute path to the directory where collectstatic will collect static files for deployment (OUTPUT). I am not sure what to put this value as
For STATICFILES_DIR This setting defines the additional locations the static files app will traverse if the FileSystemFinder finder is enabled. So I would NEED a STATICFILES_FINDER field in my settings.py and in that field would be
('django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder')
However, by default STATICFILES_DIR is not included in my settings.py so I added it in.
For STATIC_URL is the URL to use when referring to static files located in STATIC_ROOT. I simply left it as the default setting because I am not sure how edit this.
I am not sure how to edit my settings.py regarding static files in order to display them onto a webpage. What is a "Best Practices" way to include static files onto a webpage?
ex: {% static "static/css/default.css" %}
I read a bit about namespacing as well but I am confused about this too
ex:
STATICFILES_DIR = (
("asserts", os.path.join(BASE_DIR, 'static')),
)
Best practice would be keeping each app's static files in it's own 'static' dir and running manage.py collect_static each time some static file changes.
Then, if you use default storage your files would be copied into STATIC_ROOT directory.
(But you might use custom storage, for ex for storing static files on Amazon S3 cloud)
And finally, STATIC_URL defines how your static files would be accessible from outside. In case of django dev server- it has static files app, that serves them under STATIC_URL location. In case of production server you definitely want to serve static files with either nginx/apache or with amazon S3/cloudfront (or other cloud services). In case ouf serving with nginx/apache, you must set STATIC_URL so {% static "static/css/default.css" %} will be replaced with the url relative to STATIC_ROOT, at the same time you should have this STATIC_URL location overriden in nginx/apache settings, so when final user tries to access it, it gets static file served w/o even touching django. In case of custom storage- this storage might provide it's own url (to S3 cloud for ex).

Once and for all, static files vs Django 1.3

I've been trying to follow every single tutorial and thread there is, i jast cant get it togheter.
Sorry, but please exlpain it to me as if i was three years old..
What i have:
a CSS that i'd like use, styling a template.
How to get there:
MD: project/app/static/
place style.css there
settings.py:
STATIC_ROOT = '/project/app/static/'
STATIC_URL = '/static/'
(Should'nt this at least give me the string '/static/', when i try printing {{ STATIC_URL }} in the template..?)
template:
<LINK REL=StyleSheet HREF="{{ STATIC_URL }}/style.css" TYPE="text/css" MEDIA=screen>
Seems to me, the next logical thing would be to create an /static/-url aswell?
I'm really lost here..
Django's staticfiles system is about two things:
Combining static files from a number of (app-specific) directories into a single place from which they can be served
Serving those files over HTTP
You want #1 if you have a number of static files located in different directories. You want #2 if you want to see those files while you are using the development server. In production, you usually skip #2, because the purpose of #1 is to put the files somewhere that your web server can access them.
Organizing and collecting static files
With that said, here's how you get #1:
settings.py:
# This is a filesystem path
STATIC_ROOT = '/path/to/my/project/collected-static-files/'
# This is a URL prefix
STATIC_URL = '/static/'
INSTALLED_APPS = (
...
'django.contrib.staticfiles',
...
)
TEMPLATE_CONTEXT_PROCESSORS = (
...
'django.core.context_processors.static',
...
)
At this point, you can do a few things:
You put your static files in an '/static/' directory under each of your apps. That's where django will look for them. There is an additional setting, STATIC_DIRS, that you can use if you have static files that are outside of your apps.
You can run manage.py collectstatic to have Django go through all of your apps, finding all of the static files, and copying them into /path/to/my/project/collected-static-files (That's why that setting is a filesystem path.)
You can use {{ STATIC_URL }} in templates to access the files.
Serving static files over HTTP
In development mode, under the dev server, Django will automatically serve files out of the STATIC_ROOT directory.
Basically, Django will add a URL handler for URLs of the form
/static/some-dir/some-file-name
And serve content from your hard drive, from the filesystem path
/path/to/my/project/collected-static-files/some-dir/some-file-name
In production, this won't happen automatically, so you will have to configure your web server to do the same thing. (It's just not a good idea to run all of your static files through Django's full processing pipeline. The web server can do it much more efficiently)

What is the difference between static files and media files in Django?

I'm moving to Django 1.3 and find this separation of media and static files a bit confusing. Here is how default settings.py looks like:
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
# Absolute path to the directory that holds static files.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL that handles the static files served from STATIC_ROOT.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
What should I put into MEDIA_ROOT and a STATIC_ROOT? Should those be separate directories? What is the difference?
Static files are meant for javascript/images etc, but media files are for user-uploaded content.
As Uku Loskit said, static files are for things like your applications' css files, javascript files, images, etc. Media files are typically user or admin uploadable files.
Normally you will want MEDIA_ROOT and STATIC_ROOT to be separate directories. Keep in mind that STATIC_ROOT is where the management command collectstatic will place all the static files it finds. In production, you then configure your webserver to serve the files out of STATIC_ROOT when given a request that starts with STATIC_URL. If you are using the Django devserver for development, it will automatically serve static files.
The staticfiles application thus disentangles user uploaded media from application media, thus making deployment, backups, and version control easier. Prior to the staticfiles app, it was common for developers to have the media files mixed in with static application assets.
The 1.3 docs for staticfiles have been steadily improving; for more details, look at the how-to.

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