I'm getting a broken image in a django project, but as far as I have checked, the code looks right.
Here's the code in settings.py:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
I have also imported the media option in the templates section:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'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',
'django.template.context_processors.media',
],
},
},
]
Here's the code I'm using in the template.
{% if request.user.profile.picture %}
<img src="{{ request.user.profile.picture.url }}" height="35" class="d-inline-block align-top rounded-circle">
{% else %}
<img src="{% static 'img/default-profile.png' %}" height="35" class="d-inline-block align-top rounded-circle">
{% endif %}
The default-profile.png image is loading correctly, but the other profile pictures are not, although they have been loading correctly to the media folder and their urls are displayed correctly in the database. Anyone knows what I'm doing wrong?
EDIT:
The HTML output of the image is the following:
<img src="/media/users/pictures/Foto.jpg" height="35" class="d-inline-block align-top rounded-circle">
It looks correct when checking the src tag, as it matches the MEDIA_URL with the valur that was stored in the database after it.
What appears to be happening is that you're not serving the media files correctly during development. You can try appending this to the urlpatterns list on your site's urls.py file.
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Please refer to this information in the docs for more details.
Related
I know there are many posts about this, but I have been unable to resolve my problem (for example following this: Django static files (css) not working). I can't get my css static file to load on this practice page, css_practice.html.
I have the following structure
djangoAjax
settings.py
...
djangoAjaxApp
static
ok.css
templates
css_practice.html
My settings.py:
import os
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = '############################################'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
"crispy_forms",
'djangoAjaxApp',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'djangoAjax.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
WSGI_APPLICATION = 'djangoAjax.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'), BASE_DIR / "static",
]
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
)
my html page:
<!DOCTYPE html>
{% load static %}
<html>
<head>
{% comment %} https://www.bing.com/videos/search?q=django+static+css&docid=608004894969656896&mid=E118E7C4ADFE161B3B12E118E7C4ADFE161B3B12&view=detail&FORM=VIRE {% endcomment %}
{% load static %}
<link type="text/css" rel="stylesheet" href"{% static 'djangoAjaxApp\static\ok.css' %}">
<title>Page Title</title>
</head>
<body>
<h1 class="ok">My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
views.py:
# css practice
def cssRender(request):
return render(request, "css_practice.html")
urls.py:
from django.urls import path
from .views import cssRender
urlpatterns = [
path('css/', cssRender, name='cssRender'),
]
I imagine I might be messing up the folder structure somehow... there is also a reference in the django docs: https://docs.djangoproject.com/en/3.2/howto/static-files/
about adding
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
But since I am using, django.contrib.staticfiles in settings, I'm assuming this is done automatically.
Currently the page loads, but css is not applied.
Thanks for your help
settting.py:
STATIC_URL = '/static/'
Only one {% load static %} is enough in your html code:
<!DOCTYPE html>
{% load static %}
You have to Copy and Plast your STATIC files (Js, CSS, ...) in your templates.
It will look like that :
djangoAjaxApp
|_migrations
|_templates
| |_djangoAjaxApp
| |_css_practice.html
|_static
|___djangoAjaxApp (directory with the same App name)
|_(here all your static file)
Your HTML will look like this:
<link type="text/css" rel="stylesheet" href"{% static 'djangoAjaxApp\ok.css' %}">
views.py:
# css practice
def cssRender(request):
return render(request, "djangoAjaxApp/css_practice.html")
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.cssRender, name='cssRender'),
]
djangoAjax urls.py:
from django.conf import settings
from django.contrib import admin
from django.urls import path
urlpatterns = [
# ... the rest of your URLconf goes here ...
]
Could you please try it.
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
Just to remind you of it, have you tried hard refresh on your browser? I used to miss this when I was a beginner. (You can do it in chrome with ctrl+shift+r).
My css file is not getting loaded in the webpage. I have css and image file in the same location. The image is getting loaded but not the css.Also I have included the directory in staticfile_dirs.
Setting.py
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'technicalCourse.apps.TechnicalcourseConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'website.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
r'C:\Users\Kesavan\PycharmProjects\Django web development\website\technicalCourse\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',
],
},
},
]
WSGI_APPLICATION = 'website.wsgi.application'
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
r'website\technicalCourse\static',
]
This the template file
<!DOCTYPE html>
{% load static %}
<head>
<link rel="stylesheet" type="text/css" href="{% static 'css/simple.css' %}">
</head>
<body>
<img src="{% static 'image/img.png' %}">
<h1>Welcome to course on programming</h1>
<ol>
{% for x in ac %}
<li>{{x.courseName}}</li>
{% endfor %}
</ol>
</body>
For testing I simply change the color of the h1 tag alone. The css file.
h1{
color:black;
}
Structure
C:.
├───migrations
│ └───__pycache__
├───static
│ ├───css
│ └───image
├───template
│ └───technicalCourse
└───__pycache__
But there is no reflection on the webpage.
Hoping for the solution.
Thanks in advance.
try this command:
python manage.py collectstatic
and check again.
It's weird that images are working and CSS isn't. There could be a multitude of possibilities for your problem.
The simplest way to solve this is to set the path to the CSS files via an absolute or a relative path.
Relavtive path case
<link href="/static/ui/css/base.css" rel="stylesheet">
I was suffering with same problem but solved by adding the
{% load static %}
{
<link rel="stylesheet" type="text/css" href="{% static 'thumbnail_searcher/style.css' %}">
}
in same tag. For example in your case add load and link into <head> tag.
clear browser cache
in settings.py change STATIC_URL = "static/" to STATIC_URL = "/static/"
run python manage.py runserver port_number(optional)
Try
$ python manage.py findstatic css/style.css
instead of css/style.css add your own path
If Django project able to locate the CSS, it will return path to your CSS file.
Then restart your project and it should work.
I need to incorporate css in my templates to help them look better, but inspite of adding the static url and root, I am just not able to load it in my template. I am attaching the relevant code here. Please tell me what am I doing wrong. Thanks in advance.
settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
STATIC_DIR = os.path.join(BASE_DIR,'static')
STATIC_URL = '/static/'
STATIC_ROOT = [STATIC_DIR,],
index.html
<!DOCTYPE html>
{% load staticfiles %}
<html lang="en">
<head>
<link href="{% static 'css/index.css' %}">
</head>
settings.py
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'project_name/static')
]
index.html
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<link href="{% static 'css/index.css' %}" rel="stylesheet">
</head>
for more information check here
for loading static files you need to add the static url too
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
......
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
add these in your project's root url
Change url base urls.py like following
urlpatterns = [
# your url here
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Also include {% load static %} tag in your template
There is no settings named STATIC_DIR, it should be STATICFILES_DIRS and should be declared like this:
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static'),
]
STATIC_ROOT = os.path.join(BASE_DIR,'staticroot') # Static Dir and Static root needs to be different
As for serving static files, as per documentation, if you add django.contrib.staticfiles in INSTALLED_APPS, then django will serve static automatically when DEBUG is True. But in production, you need to use a reverse proxy server to static files. Or you can use whitenoise. More information can be found in documentation as well.
Which version of Django do you using? Starting from 2.0 there are some changes, instead of
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
there is
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'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',
],
},
},]
Also check out is your static folder even exist
And be sure that you have chosen right path to your static folder(for example I hold this folder inside of template folder so my code looks like this)
STATIC_URL = '/templates/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "templates/static"),]
And I see that you didn't put csrf_token to your html, so please add this to your html
{% csrf_token %}
Code snippet managed static files in settings.py as follows.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATICFILES_DIRS = [
os.path.join(
os.path.dirname(__file__),
'static',
),
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
BASE_DIR + '/templates/'
],
'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',
],
'loaders': [
('django.template.loaders.cached.Loader', [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
]),
],
'debug' : True
},
},
]
STATIC_URL = '/static/'
url.pyfile is as follows.
from django.conf.urls import include, url
from django.contrib import admin
from tweets.views import Index, Profile
admin.autodiscover()
urlpatterns = [
url(r'^$', Index.as_view()),
url(r'^admin/', include(admin.site.urls)),
url(r'^user/(\w+)/$', Profile.as_view()),
]
views.pyfile is as follows
{% load staticfiles %}
<html>
<head>
<title>Django</title>
<link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}" media="screen">
</head>
<body>
{% block content %}
<h1 class="text-info">Hello {{name}}!</h1>
{% endblock %}
<script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script>
</body>
</html>
When I run server, browser can't find bootstrap.min.js file.
Page not found at /static/bootstrap/css/bootstrap.min.css
http://localhost:8000/static/bootstrap/css/bootstrap.min.css
'bootstrap/css/bootstrap.min.css' could not be found
It seems that the static files url is correct.
But browser can't find the static files.
Please tell me the reason and how can I handle it?
To serve the static files during development you should add to your urls.py the following code:
from django.conf.urls import include, url
from django.contrib import admin
from tweets.views import Index, Profile
from django.conf import settings
from django.conf.urls.static import static
admin.autodiscover()
urlpatterns = [
url(r'^$', Index.as_view()),
url(r'^admin/', include(admin.site.urls)),
url(r'^user/(\w+)/$', Profile.as_view()),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
And you should create the path in your project folder static/your_app/your_files
http://docs.djangoproject.com/en/dev/howto/static-files/
This suggests that I can use STATIC_URL in my template to get the value from settings.py.
Template looks like this:
<link href="{{STATIC_URL}}stylesheets/tabs.css" rel="stylesheet" type="text/css" media="screen" />
Settings.py looks like this:
STATIC_ROOT = ''
STATIC_URL = '/static/'
When I go to the page I just get <link href="stylesheets/tabs.css" i.e. no STATIC_URL.
What am I missing?
You have to use context_instance=RequestContext(request) in your render_to_response, for example:
return render_to_response('my_template.html',
my_data_dictionary,
context_instance=RequestContext(request))
Or use the new shortcut render
As Dave pointed out, you should check if django.core.context_processors.static is in your TEMPLATE_CONTEXT_PROCESSORS variable in settings.py. As the docs said, it`s there by default.
It is not recommended to directly use the STATIC_URL variable. See the accepted answer in this question
Instead of
{{STATIC_URL}}stylesheets/tabs.css
use
{% load staticfiles %}
{% static 'stylesheets/tabs.css' %}
I have the same problem, solved like this:
in settings.py
add:
django.template.context_processors.static
here:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': TEMPLATE_DIRS,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.template.context_processors.static',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]