Cannot load static content in Django - django

I am setting up a beginner django app and I cannot make it display static content. (css and jpg) files. The documentation is confusing and I need some help at a very basic level.
My static files are located in: '/home/me/django_projects/myproject/site_media'. Under here there are directories: 'images' and 'css'
I am getting 404 errors on everything static. Even if I try to pull the file directly from: http://localhost:8000/site_media/images/test_image.jpg
Here is the html code that I that is supposed to trigger static content:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="keywords" content="" />
<meta name="description" content="" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Django Test </title>
<link href="{{ STATIC_URL }}/css/style.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
This is my body... blah blah blah
<p>Here is an image: <img src="{{ MEDIA_URL }}images/media.jpg" alt="Foobar" />
</body>
Below are my settings files. I've tried about every combination of media and static configuration I can think of. Does anyone see what I am doing wrong here?
File: settings.py
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = '/home/me/django_projects/myproject/site_media/'
MEDIA_URL = '/media/'
ADMIN_MEDIA_PREFIX = '/admin_media/'
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = (
"/home/me/django_projects/myproject/static",
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
#...
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'jim',
)
File: urls.py
urlpatterns = patterns('',
(r'^customers/$', 'jim.views.index'),
(r'^customers/(?P<customer_id>\d+)/$', 'jim.views.detail'),
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/media'}),
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/media'}),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
)
Does anyone see whats wrong here?

Looks like you might have two forward slashes:
STATIC_URL = '/static/'
"{{ STATIC_URL }}/css/style.css"
would give you
"/static//css/style.css"
view the page source in the browser and see how the url is being written

If I look at your config I would expect the file at:
http://localhost:8000/media/images/test_image.jpg
But please read the django docs on static versus media. Media is for useruploaded content, static is for site-content like css/images.

Related

Can't link my css file in my django project

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">
<link rel="stylesheet" href="{% static 'style.css' %}">
<title>Document</title>
</head>
<body>
<h1 class="heading">This is the Heading</h1>
</body>
</html>
settings.py (my app name is base)
from pathlib import Path
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',
'base'
]
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 = 'testpro.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [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 = 'testpro.wsgi.application'
...
STATIC_URL = 'static/'
STATICFILES_DIRS = BASE_DIR, 'static'
Folder structure is like this:
project folder
/static
/style.css
CSS contains a simple color change and it is not working.
I've tried linking the css file in different ways and nothing seems to be working. I don't know how or why but sometimes it suddenly works and then suddenly stops working.
Instead of this:
STATIC_URL = 'static/'
STATICFILES_DIRS = BASE_DIR, 'static'
Try this:
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
You don't need to specify base directory in templates array.
DIRS': [BASE_DIR, 'templates'],
Just let it be empty.
DIRS': [],
and all other looks fine just make sure about CSS files. and it's location.
add this to the
<head>
<link href="{%static 'style.css'%}" rel="stylesheet">
</head>
and
add this to the testpro (urls.py)
from testpro import settings
urlpatterns = [
// here goes your urls
]
//at the bottom add this
urlpatterns += static(settings.STATIC_URL , document_root=settings.STATICFILES_DIRS)
and in the settings.py
change
STATICFILES_DIRS= BASE_DIR, 'static' to
STATIC_ROOT = os.path.join(BASE_DIR,'static')
Change this part of the settings.py to something like this:
STATIC_URL = 'static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, '<Your APP name goes here>\static'),)
If you have an 'css' subfolder inside your static folder then you need to add that to the relative path in your HTML template like this:
{% 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">
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<title>Document</title>
</head>
<body>
<h1 class="heading">This is the Heading</h1>
</body>
</html>
I hope that helps you!

Django static files not working in localhost

I have my Django app running on a development server. The HTML templates are serving fine but I'm really having a lot of trouble getting the static files to serve. I've tried lots of ideas from Stack Overflow but not getting anywhere.
I just get a 404 error on the image.
Can anyone help me please?
My urls.py is:
from django.contrib import admin
from django.urls import path
from app import views
from django.contrib.auth import views as auth_views
from django.conf.urls.static import static
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# The rest of my urls here...
urlpatterns = [
path('', views.index, name='index'),
path('admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
my settings has included:
STATIC_ROOT = "/home/me/django-test/djangoproject/static"
STATIC_URL = 'static/'
and my template has:
<!doctype html>
{% load static %}
<img src="{% static 'e.png'%}">
It worked for me in django 3.2.
For local static you should create folder called "static" in your config folder
config it's folder created when you start project(may be you call it mysite or smth):
django-admin startproject config
create a "static" folder in the same folder where you have the file settings.py
#In settings.py:
STATIC_URL = '/static/'
# folder for static when you deploy your project on server(not for local develop)
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# local (in config for runserver)
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "config/static"),
]
Inside folder "static" place your css, js, img e.t.c folders
In our templates you have to do something like this:
<!DOCTYPE html>
{% load static %}
<html lang="ru">
<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">
<link rel="stylesheet" href="{% static 'css_custom/base_style.css' %}"/>
<title>{% block title %}TITLE{% endblock title %}</title>
</head>
Pay attention to my template tag
href="{% static 'css_custom/base_style.css' %}"
that means i load static from:
config/static/css_custom/base_style.css
Same thing for load image, in you template.html:
{% extends '_base.html' %}
{% load static %}
{% block content %}
<img src="{% static 'images/Bg.jpg' %}" alt="">
{% endblock content %}
that means static from:
config/static/images/Bg.jpg
or you can add relative path into your style.css for some classes like:
.header-home {
height: 40vh;
background-image: url("../images/Bg.jpg");
background-size: cover;
background-position: center;
text-align: center;
}
Hope it helps you

How i can add static files (css) to django web project

I have tested to embedded css style into html template, but it doesn't load css files, my configure as below, could you please help assist ?
checkstatic\showstatic\templates\index.html
<!DOCTYPE html>
<meta charset="UTF-8">
<html lang="en">
<head>
{% load static%}
<link rel="stylesheet" type="text/css" href="{% static 'css/mystyle.css' %}">
</head>
<body>
<img src="{% static 'logo1.png' height="200" width="200" class="d-inline-block align-top" %}" alt="">
<h1 class="test">hahahaha</h1>
</body>
</html>
checkstatic\static\css\mystyle.css
.test{
color: red;
}
my settings:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'showstatic'
]
...
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'checkstatic/static/')
]
when i access the index site, it only apply h1 tag, it can not load red color as the css config.
Statics are used to get and use complete files (css, images, js, etc), in your image it should be:
<img src="{% static 'logo1.png' %}" height="200" width="200" class="d-inline-block align-top" alt="">
Leaving the properties of the img outside the static block.
first you should create directory=> static*
after then add base directory in setting:
STATICFILES_DIRS = [
BASE_DIR / 'directory_name'] // typically the name is: static_root
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR , 'media')
then: insert urls in main project
from django.conf import settings
from django.conf.urls.static import static
+static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT)
!!attention !! ==> you should insert {%load static %} at above each of html pages
if you want to know more, follow https://docs.djangoproject.com/en/4.0/howto/static-files/

Unable to load Static files into my Index.html in Django

I am new to Django and I am having a challenge in importing static files into my main HTML document. Can anybody help? Below is the approach I am following
My project structure looks like below. Hi2 is the project
settings.py looks like below. I did all the Important settings related to Static Files
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
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')
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp'
]
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
STATICFIELS_DIRS=[
STATIC_DIR,
]
My view file looks like below
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request,'myapp/index.html')
Finally imported CSS into my index.html in the below way. In the 3rd line Used {% load static %} and in 14th and 17th lines used "{% static "file location" %}". But it's not all reflecting when viewd Index.html page.
1) <!DOCTYPE html>
2) <html lang="en">
3) {% load static %}
4) <head>
5)
6) <meta charset="utf-8">
7) <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
8) <meta name="description" content="">
9) <meta name="author" content="">
10)
11) <title>Home</title>
12)
13) <!-- Bootstrap core CSS -->
14) <link href="{% static 'myapp/vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">
15)
16) <!-- Custom styles for this template -->
17) <link href="{% static 'myapp/css/simple-sidebar.css' %}" rel="stylesheet">
18)
19) </head>
Any help is highly appreciated
Thanks In Advance
Venk

Why is the logo not showing on my site? GET /static/img/ATbrAaMRc.jpg HTTP/1.1" 404 1778 is the error i am getting

I am trying to add a logo to my site, but for some reason it just isn't showing up.I have configured my code to the best of my knowledge but here is my code.
First i made sure django.contrib.staticfiles is included in my INSTALLED_APPS.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
]
i then ensured i defined STATIC_URL in my settings.py. I am only using one STATIC
STATIC_URL = '/static/'
STATICFILES_DIR = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
In my templates, i used the static template tag to build the URL for the relative path using the configured STATICFILES_STORAGE
{% load static %}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
{% block title%}
{% endblock title%}
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="{%url 'index' %}">
<img src="{% static 'img/ATbrAaMRc.jpg' %}" alt='Image'>
</a>
Any help is appreciated.
There was a typo in the original post.
STATICFILES_DIR was used instead of STATICFILES_DIRS (Note the "S" at the end).
Fixing this allowed the "static" folder to be stored outside of the "blog" folder.
(Source: https://docs.djangoproject.com/en/3.0/howto/static-files/)
moving the static folder to the blog app worked.