i am unable to load static files with django in my template my files are shown below
Settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Theme'
]
STATIC_DIR = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIR = [
STATIC_DIR,
]
Template/index.html
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>First App</title>
</head>
<body>
<h1>Hello this is index.html!</h1>
<img src="{% static 'images/mark.jpg' %}" alt="My image">
</body>
</html>
project Direstory
This is the projec t directory`
Add these code also in your main url file
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
and in setting add this line too
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static")
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media")
STATICFILES_DIR list should be named STATICFILES_DIRS.
In development when you run with runserver and DEBUG=True it is enough.
To serve staticfiles in production:
usage of external web-server (in production you will most probably have one or web-proxy in front of django) is recommended. Call collectstatic
and serve the resulted static_root dir with web-server
Or you can upload them to CDN (AWS S3, CLoudflare)
Or it is possible to make django serve them using Whitenoise
least recommended but still possible - serving with django as is development by adding static urls
Related
My static files are not loading on Django. I'm running this on my local machine. The location of example.png is main/static/main/example.png. main is an app.
Here's my settings.py:
from pathlib import Path
import os
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'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 = 'tutorials.urls'
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR, ],
'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 = 'tutorials.wsgi.application'
...
STATIC_URL = 'static/'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
My template, index.html:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<nav>
<div class="logo">
Tutorials.
</div>
</nav>
<img src="{% static 'main/example.png' %}" alt="My image">
</body>
</html>
The static files called for in index.html do not load. The alt text is seen.
First of all I think you have not configured your static files and media files. Try configuring it as follows. In your settings.py ensure to include STATICFILES_DIR, STATIC_ROOT, MEDIA_URL, MEDIA_ROOT in your settings.py and then add the below lines below STATIC_URL = 'static/'
MEDIA_URL = 'media/'
STATICFILES_DIRS = [BASE_DIR / 'static']
STATIC_ROOT = BASE_DIR / 'staticfiles/'
MEDIA_ROOT = BASE_DIR / 'static/media'
By doing this you are telling django where to get your static files. now your have to add the link of the static files in your project urls.py. you will add that as below.
from django.conf import settings
from django.conf.urls.static import
static
urlpatterns = [
.......
]
urlpatterns +=
static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
One last thing that I assumed you had done is creating static folder in your project root and inside that static folder create media folder where all the images you want to load are.
Now run python manage.py collectstatic
I am learning django, I would like to read a json file but I do not kown where to put it cause I cannot display.
I have place the file in the folder "static_project" but it is not working
Here is the structure of my project:
src=>templates=> Main=> home.html
src=>Myproject=> settings.py
src=>Myproject=>urls.py
here the html:
{% load static %}
<lottie-player
src= src="{% static "./myfile.json" %}" background="transparent" speed="1" style="width: 700px; height: 700px;" loop autoplay >
</lottie-player>
</div>
Hereis the main urls.py
if settings.DEBUG:
import debug_toolbar
urlpatterns += [
path('__debug__/', include(debug_toolbar.urls)),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Here is my setting :
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static_project")
]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn", "static_root")
#every time a user upload folder, it will be inside the static_cdn folder and the root "media root"
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn", "media_root")
Thanks for your help
static folder path correct and it was all working before migration.
index.html
{%load staticfiles%}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="{% static "css/mycss.css"%}"/>
<title>My first Django App</title>
</head>
<body>
<h1>{{somthin}}</h1>
<img src="{% static 'images/zoro.jpg'%}" alt="Oops!No Image">
</body>
</html>
after python manage.py runserver in terminal static files are showing 404 error.
make sure all these configuration you have in your settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static")
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media")
and in main urls.py
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
and use {% load static %} tag in templates, also if you use double quote outside curly brackets, use single quote inside
<link rel="stylesheet" href="{% static 'css/mycss.css' %}"/>
my html
<!DOCTYPE html>
{% load static %}
<html>
<head>
<title>Fish store</title>
<link rel="stylesheet" type="text/css" href="{% static 'css/animate.css' %}">
</head>
<body>
<h2>Home page</h2>
</body>
</html>
my settings.py
INSTALLED_APPS = [
'fish.apps.FishConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
in fish app I have static folder and css folder, and then animate.css
fish/static/css/animate.css
main url
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.index)
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Now I try to access http://localhost:8000/static/css/animate.css
it shows:
Not Found
The requested resource was not found on this server.
I am designing a website using django, following the steps of a course that I've enrolled recently. All the code & resources have been provided to me. I'm following each and every step accordingly but the layout of my website is not similar to what I'm following.
I faced similar problem when I was trying on similar project that I tried before the current one. The layout of my website is way too simple. I'm using the latest versions so i guess there maybe something that I've to include. The image is also not displaying on my website.
It would be really helpful if someone let me know what am I missing.
This is what I'm expecting:/
This is what I'm getting:(
This is my main html file:-
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- Font Awesome -->
<link rel="stylesheet" href="{% static 'css/all.css' %}">
<!-- Bootstrap -->
<link rel="stylesheet" href="{% static 'css/bootstrap.css' %}">
<!-- Custom -->
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<!-- Lightbox -->
<link rel="stylesheet" href="{% static 'css/lightbox.min.css' %}">
<title>Django Website</title>
</head>
<body>
<!--Top bar-->
{% include 'partials/_topbar.html' %}
<!--Nav bar-->
{% include 'partials/_navbar.html' %}
{% block content %}
{% endblock %}
<!--Footer-->
{% include 'partials/_footer.html' %}
<script src="{% static 'js/jquery-3.3.1.min.js' %} "></script>
<script src="{% static 'js/bootstrap.bundle.min.js' %} "></script>
<script src="{% static 'js/lightbox.min.js' %} "></script>
<script src="{% static 'js/main.js' %} "></script>
</body>
</html>
This is my settings.py:-
"""
Django settings for Django_Project project.
Generated by 'django-admin startproject' using Django 2.2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'gwdbwxvan^9g5z-r$g9rf=!zeqrvu*2#^uye!ae#95my3dqp&t'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'pages.apps.PagesConfig',
'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 = 'Django_Project.urls'
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',
],
},
},
]
WSGI_APPLICATION = 'Django_Project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
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/2.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/2.2/howto/static-files/
STATIC_ROOT= os.path.join(BASE_DIR,'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'Django_Project/static')
]
You need to collect static files, in your terminal:
django-admin collectstatic
Also here is the official documentation how to handle static files
Unless inside the templates(html files), you did something wrong with extend layout. In that case you might find this link helpful and this
Also if you could provide the code of the HTML files that would be really helpful.
At your settings files at the end add these lines
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
I think you have done something wrong with static files and media file path.
Please check your static file path and media path.
For example you should define the following things in settings.py file
# Static files (CSS, JavaScript, Images)
import os
BASE_DIR = os.path.dirname(__file__)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Also, make sure that the static files and media folder present in the project.
You need to import your static folder in each template
{% load static %}
Then you can access your static files and put it for example in image "scr" tag.
src="{% static 'img/your_image.svg' %}"