I am studying Django. In my settings.py :
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
and when I try to add an image in a template,
<img src="{% static "img/person.png" %}"/>
<img src="{{ STATIC_URL }}img/person.png" />
<img src="/static/img/person.png" />
All three are shown in the browser as:
<img src="/static/img/person.png" />
Then, What is the different between them?
If there is no problem, can I use
<img src="/static/img/person.png" />
in the template code?
The problem with hardcoded URLs <img src="/static/img/person.png" /> is that if in future you want to change static URL you have to go through all files to replace it with newer one, and usually in production sometimes we want to use CDN to serve static content and that is not served via /static/.
For the other difference between {% static %} and {{ STATIC_URL }} check this answer.
Related
I have a django project that structure is like this:
>vira
>vira
-__init.py
-settings.py
-urls.py
-wsgi.py
>vira_app
>migrations
>template
-index.html
>static
>vira_app
>assets
>css
>js
>vendor
>aos
>bootstrap
>bootstrap-icons
>isotope-layout
>swiper
-__init__.py
-admin.py
-apps.py
-models.py
-tests.py
-urls.py
-views.py
-db.sqlite3
-manage.py
I have used bootstrap. index.html is like below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
{% load static %}
<link href="{% static 'vira_app/assets/vendor/aos/aos.css' %}" rel="stylesheet">
<link href="{% static 'vira_app/assets/vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">
<link href="{% static 'vira_app/assets/vendor/bootstrap-icons/bootstrap-icons.css' %}" rel="stylesheet">
<link href="{% static 'vira_app/assets/vendor/swiper/swiper-bundle.min.css' %}" rel="stylesheet">
{% load static %}
<link href="{% static 'vira_app/assets/css/style.css' %}" rel="stylesheet">
</head>
<body>
<main id="main">
<div id="portfolio-grid" class="row no-gutter" data-aos="fade-up" data-aos-delay="200">
{% if catalogue_list %}
{% for Catalogue in catalogue_list %}
<div class="item web col-sm-6 col-md-4 col-lg-4 mb-4">
<a href="{{ Catalogue.link }}" class="item-wrap fancybox">
<div class="work-info">
<h3>{{ Catalogue.title }}</h3>
<span>{{ Catalogue.source }}</span>
</div>
<img class="img-fluid" src="{{ Catalogue.image }}">
</a>
</div>
{% endfor %}
{% endif %}
</div>
</div>
</main>
<i class="bi bi-arrow-up-short"></i>
<script src="assets/vendor/aos/aos.js"></script>
<script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="assets/vendor/isotope-layout/isotope.pkgd.min.js"></script>
<script src="assets/vendor/php-email-form/validate.js"></script>
<script src="assets/vendor/swiper/swiper-bundle.min.js"></script>
<script src="assets/js/main.js"></script>
</body>
</html>
settings.py:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'vira_app', 'template')
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
STATIC_URL = '/static/'
STATIC_ROOT = '/vira_app/template'
When I run the server and go to index.html, data retrieved from db and show well, but without any style!
I have tried some solution, check every static url, but not working
In fact, css, js and vendors not applied. What's the problem?
Some of settings are misused:
STATIC_URL = '/static/' - this is fine
STATIC_ROOT = '/vira_app/template' - nope, this is supposed to be some folder not really related to the project structure. In the end, on prod it can be a CDN URL or a folder on different server. So try changing it to something like STATIC_ROOT = os.path.join(BASE_DIR, 'static') for the start.
As mentioned in comments you might need to define STATICFILES_DIRS - a list of folders where from static files must be collected to STATIC_ROOT by collectstatic command. This means you can have many subfolders containing static files in different places. However you'll need to collect those files all together to deploy somewhere. STATICFILES_DIRS + collectstatic will collect all of those files for you into given STATIC_ROOT (and contents of this folder should be deployed somewhere, to CDN for example).
Note, default set of STATICFILES_FINDERS already contains AppDirectoriesFinder which will automatically find all the static subfolders in any of the project apps. This means if you move static subfolder from templates to the vira_app root - you won't have to mention it in the STATICFILES_DIRS.
So:
STATIC_ROOT should not point to any templates subfolders, change it to something more "global"
STATICFILES_DIRS should link to the folder(s) where you keep your static files now or this folder should be moved to the root of vira_app to let collectstatic find it
collectstatic must be run before checking your styles and scripts in rendered page
after running collectstatic all the static files must persist in STATIC_ROOT so django will be able to map relative urls after STATIC_URL to relative paths after STATIC_ROOT and those files will be loaded
PS
Note, some of your static files are linked in wrong way in the shown template:
<script src="assets/vendor/aos/aos.js"></script>
this should be changed to {% static... as well.
I have the media url and media root as follows.
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, MEDIA_URL)
my urls.py is
if settings.DEBUG:
# static files (images, css, javascript, etc.)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I am accessing it in the template as follows:
<img class="hl" src="{{ MEDIA_URL }}prop/image0.png" /></a>
The url replaced when rendered is correct, which is /media/prop/image0.png.
But it says the media location is not found.
I suggest you use staticfile for this purpose, because you are using a specific image and not something that will be uploaded in the future.
If you decide to use static files, put the image in your static folder and then use this:
<img src="{% static 'image0.png' %}" style="">
Don't forget to load your staticfiles:
{% load staticfiles %}
By the way, for future, if you wanted to use media files in your templates you have to do it like this:
{% for image in images %}
<img src="{{ image.url }}" class="h1">
{% endfor %}
please help bring images into the template
in django1.6 I uploaded via the form in the database image. screenshot. ( checked that the images loaded in a specific directory ) . then imported into the template file settings.py variable BASE_DIR and to all records of a table . then tried in the template to display the image as follows:
{% for entrie in all_entries_carousel %}
<a href="{{ entrie.link }}" title="{{ entrie.title }}" target="_blank">
<img src="{{ BASE_DIR }}/{{ entrie.image }}" width="300" height="200" alt="{{ entrie.title }}" />
</a>
{% endfor %}
results in images that I have not loaded and displayed.
in the source path
c:\Python33\django_projects\proj1/carousel/media/images/img1.png
please tell me how can I still display the image. Sure , there is a path without importing BASE_DIR
ps this way does not work proj1/carousel/media/images/img1.png
You need to configure your static files.
From Django docs:
Make sure that django.contrib.staticfiles is included in your
INSTALLED_APPS.
In your settings file, define STATIC_URL, for example:
STATIC_URL = '/static/'
In your templates, either hardcode the url like
/static/my_app/myexample.jpg or, preferably, use the static template
tag to build the URL for the given relative path by using the
configured STATICFILES_STORAGE storage (this makes it much easier
when you want to switch to a content delivery network (CDN) for
serving static files).
{% load staticfiles %}
<img src="{% static "my_app/myexample.jpg" %}" alt="My image"/>
Store your static files in a folder called static in your app. For
example my_app/static/my_app/myimage.jpg.
This question already has answers here:
Django template image won't load
(4 answers)
Closed 9 years ago.
Image wan't load.I see o broken image icon.I use the static tag. I also tried giving the absolute path and never worked.I used the alt tag but still i can only see the broken image icon. Is the tag correct what else should i try ??? The images is in static\images\logo.png
base.html
{% load static %} {# loads static tag #}
<div id="header">
{% block header %}
<img src="{% static 'images/logo.png' %}" alt="alternative text" />
{% endblock %}
</div>
setting.py:
MEDIA_ROOT = ''
MEDIA_URL = '/media/'
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = ('assets','C:\Users\#########\workspace\project\static'),
Try either
<img src="{{ STATIC_URL }}images/logo.png" alt="alternative text" />
or fixing your quotes
<img src="{% static 'images/logo.png' %}" alt="alternative text" />
and fixing your settings
STATICFILES_DIRS = ('assets', r'C:\Users\#########\workspace\project\static'),
or
STATICFILES_DIRS = ('assets','C:\\Users\\#########\\workspace\\project\\static'),
It's worth asking whether or not you've used Django's collectstatic method after including the image in your assets folder.
I am using django 1.5.2 and I am having a hard time understanding the purpose of the media directory vs. the static directory and how to include stylesheets in my django project.
This is my directory structure:
django_books
beer
__init__.py
admin.py
models.py
views.py
random_book
(same as beer above)
django_books (the actual django project; beer and random_book above are my apps)
templates
base.html
beersall.html
__init__.py
settings.py
urls.py
views.py
wsgi.py
static
css
beers.css
media
css
beers.css
static
css
beers.css
manage.py
My beersall.html template (the beer output is correct, so just linking the stylesheet is wrong):
{% extends 'base.html' %}
{% block content %}
<div id="beer_list">
{% for beer in beers %}
{{ beer }},
{% endfor %}
</div>
{% endblock %}
My base.html file:
<html>
<head>
<link rel="stylesheet" type="text/css" href="/media/css/beers.css" />
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/beers.css" />
<link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}css/beers.css" />
<link rel="stylesheet" type="text/css" href="/static/css/beers.css" />
<link rel="stylesheet" type="text/css" href="/Users/username/Projects/django_books/media/beers.css" />
<link rel="stylesheet" type="text/css" href="/Users/username/Projects/django_books/static/beers.css" />
<link rel="stylesheet" type="text/css" href="/Users/username/Projects/django_books/django_books/static/beers.css" />
{% block extrahead %}{% endblock %}
</head>
<body>
<div id="page_container">
{% block content %}
{% endblock %}
</div>
</body>
</html>
My settings.py file:
MEDIA_ROOT = '/Users/username/Projects/django_books/media/'
MEDIA_URL = '/Users/username/Projects/django_books/media/'
STATIC_ROOT = ''
STATIC_URL = '/static/'
I should note that I am using the django development server, not apache.
The error in my browser (developer console) says beers.css is 404.
The url is localhost:8000/beers/ and my urls.py file correctly points to this and the views.py correctly serves the beersall.html template. How can I properly link my media?
EDIT
When I change the css link href value to /Users/username/Projects/django_books/media/ it still doesn't work.
EDIT 2
I've updated the href values to show things I've tried. Still not working...
User-uploaded files (by admins or site users) go to media directory.
Static files are files provided by developers (or from third-party apps).
Set something like this:
# Local disk paths
MEDIA_ROOT = '/Users/username/Projects/django_books/media/'
STATIC_ROOT = '/Users/username/Projects/django_books/static/'
# URLs visible in the browser's address bar
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
And in Your template use the STATIC_URL variable:
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/beers.css" />
And move your styles to the django_books/static/ directory.
in my project:django_learn, in template: check_uncheck_all.html, part pf the code:
{% load staticfiles %}
<html>
<head>
<script type=text/javascript src="{% static 'js/jquery-1.9.1.js' %}"></script>
</head>
you can also have a look at my settings.py
The static files were being found, but the permissions were not set up correctly. (i.e. a 403 not a 404 server error)
<VirtualHost *:80>
WSGIScriptAlias / /Users/username/Projects/django_books/django_books/django.wsgi
#the directory tag before was /Users/username/Projects/django_books/django_books/>
#this was one directory too deep
#from my structure above, you can see I needed to change my directory tag to this:
<Directory /Users/username/Projects/django_books/>
Order Allow,Deny
Allow from All
</Directory>
<Directory /Users/username/.virtualenvs/django_books/lib/python2.7/site-packages/django/contrib/admin/static/admin/>
Order Allow,Deny
Allow from All
</Directory>
Alias /static/admin/ /Users/username/.virtualenvs/django_books/lib/python2.7/site-packages/d$
Alias /static/ /Users/username/Projects/django_books/static/
</VirtualHost>