Static files are not loading from Static folder - python

I am Building a BlogApp and I am stuck on an Problem.
The Problem
Static Files are not loading from static folder. Some files are loading but some are not loading.
What have i done ?
urls.py
I also put static url in urls.py , it also didn't work for me.
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
settings.py
os.path.join(BASE_DIR, "static", "static")
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn')
my_template.html
{% load static %}
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:400,600" />
<!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" />
<title>Next Level - Gallery</title>
<!--
Next Level CSS Template
https://templatemo.com/tm-532-next-level
-->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:400,600" />
<script src="{% static 'comments/all.min.css' %}"></script>
<script src="{% static 'comments/bootstrap.min.css' %}"></script>
<script src="{% static 'comments/templatemo-style.css' %}"></script>
</head>
<div class="row tm-welcome-row">
<div class="col-12">
<div
class="tm-welcome-parallax tm-center-child"
data-parallax="scroll"
data-image-src="static/images/blooming-bg.jpg"
>
<div class="tm-bg-black-transparent tm-parallax-overlay">
<h2>Our Gallery</h2>
<p>this is a parallax background image</p>
</div>
</div>
</div>
</div>
<div class="tm-page-col-right">
<div class="tm-gallery" id="tmGallery">
<div class="tm-gallery-item category-1">
<figure class="effect-bubba">
<img
src="static/comments/gallery/gallery-item-01.jpg"
alt="Gallery item"
class="img-fluid"
/>
</figure>
</div>
</div>
</div>
</div>
</section>
<script src="{% static 'comments/jquery.min.js' %}"></script>
<script src="{% static 'coments/parallax.min.js' %}"></script>
<script src="{% static 'comments/imagesloaded.pkgd.min.js' %}"></script>
<script src="{% static 'comments/isotope.pkgd.min.js' %}"></script>
<script src="{% static 'comments/bootstrap.min.js' %}"></script>
<script>
$(function() {
/* Isotope Gallery */
// init isotope
var $gallery = $(".tm-gallery").isotope({
itemSelector: ".tm-gallery-item",
layoutMode: "fitRows"
});
// layout Isotope after each image loads
$gallery.imagesLoaded().progress(function() {
$gallery.isotope("layout");
});
$(".filters-button-group").on("click", "a", function() {
var filterValue = $(this).attr("data-filter");
$gallery.isotope({ filter: filterValue });
console.log("Filter value: " + filterValue);
});
/* Tabs */
$(".tabgroup > div").hide();
$(".tabgroup > div:first-of-type").show();
$(".tabs a").click(function(e) {
e.preventDefault();
var $this = $(this),
tabgroup = "#" + $this.parents(".tabs").data("tabgroup"),
others = $this
.closest("li")
.siblings()
.children("a"),
target = $this.attr("href");
others.removeClass("active");
$this.addClass("active");
// Scroll to tab content (for mobile)
if ($(window).width() < 992) {
$("html, body").animate(
{
scrollTop: $("#tmGallery").offset().top
},
200
);
}
});
});
</script>
</body>
</html>
What have i tried
I also try python manage.py collectstatic and it showed 0 static files copied to 'D:\myapp\static_cdn', 248 unmodified.
I tried many answers AND some of were saying that add static url in urls.py` BUT it didn't work.
I don't know what to do
Any help would appreciated
Thank You in Advance

make sure that your settings.py has the following
settings.py
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATE_DIR = os.path.join(BASE_DIR,"templates")
STATIC_DIR = os.path.join(BASE_DIR,"static")
MEDIA_DIR = os.path.join(BASE_DIR, 'media')
the below preferably at the bottom end
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
STATIC_DIR,
]
#MEDIA
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'
LOGIN_URL = 'user_login'
now create a folder called static in the base directory( the place where you have your manage.py ) and have your static files inside
make sure to {% load static %} in your template
if nothing works try opening a new project and try the above

However static files dir is different from static files directory.Django uses 2 types of static folder . system & apps
You need to put all your static files into static files dir location then run python manage.py collectstatic . It will move all your applications static files to system static folder.
Now it will served from destination(systems static files directory) location.

Related

Django templates not picking static files

Following is the my static folder structure:
ProjectABC
- App1
- App2
- App3
- ProjectABC
- resources
- static
- imgs
- css
- templates
This is how the project structure looks like.
This is how the static configuration in settings.py looks like:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
This is how the base.html looks like:
<!doctype html>
{% load static %}
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, maximum-scale=1, initial-
scale=1, user-scalable=0">
<meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?
family=Open+Sans:400,600,800">
<title>{{SITE_NAME}}</title>
<link rel='shortcut icon' href= "{% static 'img/favicon.png' %}"/>
<link href="{{STATIC_URL}}css/application.css" media="screen" rel="stylesheet"
type="text/css" />
<link href="{{STATIC_URL}}css/style.css" media="screen" rel="stylesheet"
type="text/css" />
<script src="{{STATIC_URL}}js/application.js" type="text/javascript"></script>
{% block extracss %}
{% endblock %}
</head>
<body>
<div class="container">
<h1>Hello</h1>
</div>
</body>
</html>
All the static files are being loaded as seen in terminal, but in browser its just loading bare html without any css or img:
Please lemme know if i am missing something.
Thnk You!
<link href="{%static 'css/style.css' %}" media="screen" rel="stylesheet"
type="text/css" />
add settings.py
STATIC_URL = "/static/"
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
Project App Url
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Static directory must be under the app itself. Create a 'static' directory directly to your app and for better practice, you can also create another directory to the static directory with your app name (static/[app_name]).
Also, {% load static %} must be above doctype in your base.html
change the static config in your settings.py to this:
STATIC_ROOT = os.path.join(BASE_DIR, 'resources/static')
STATIC_URL = 'resources/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'ProjectABC')
]
then run python manage.py collectstatic
and when you call the static file do it like this {% static 'css/style.css' %}

No static files on static page in django

I have a static website in django at: domain.com/press/. The page at this address is visible, but there is a problem with static files - they don't appear.
Error in console (F12):
domain.com/press/%7B%%20static%20'images/presslogo.png'%20%%7D Failed to load resource: the server responded with a status of 400 (Bad Request)
My settings in nginx:
location /press/ {
alias /path_to_templates/;
index press.html;
}
Part of my html code:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Press</title>
</head>
<body>
<img src="{% static 'images/presslogo.png' %}">
</body>
</html>
setting.py
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
How can I display an image on a static page?
/press/ is being served by nginx. Hence <img src="{% static 'images/presslogo.png' %}"> will not work.
Please give exact path of your image. That is
<img src="domain.com/<your-static-url>/images/presslogo.png">

Cannot resolve symbol Static

{% load staticfiles %}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="{% static 'search/style.css' %}">
This is the code and I am getting error in loading static file in this part
href="{% static 'search/style.css' %}
error cannot resolve directory "{%static search
Are your settings pointing to that (search/style.css)directory? You'll need something like the following in your app's settings.py:
...
STATIC_URL = '/search/'
STATIC_ROOT = os.path.join(BASE_DIR, 'search')

Django and Angular 2 templateUrl

I've decided to integrate an existing Angular 2 app into my Django REST project.
create Django app with static folder for my frontend:
urls.py:
from django.conf.urls import url
from frontend import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^$', views.index, name='index'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
views.py:
from django.shortcuts import render
def index(request):
"""
Renders the Angular2 SPA
"""
return render(request, template_name='index.html')
move my Angular 2 app to frontend static folder
add static settings in my settings:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'frontend', 'static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
make changes in index.html:
<html>
<head>
<base href="/">
<title>PhotoHub</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
{% load staticfiles %}
<link rel="stylesheet" href="{% static "node_modules/bootstrap/dist/css/bootstrap.min.css" %}">
<link href="{% static "bower_components/font-awesome/css/font-awesome.min.css" %}" rel="stylesheet" />
<link href="{% static "bower_components/alertify.js/themes/alertify.core.css" %}" rel="stylesheet" />
<link href="{% static "bower_components/alertify.js/themes/alertify.bootstrap.css" %}" rel="stylesheet" />
<link rel="stylesheet" href="{% static "styles.css" %}">
<script src="{% static "bower_components/jquery/dist/jquery.min.js" %}"></script>
<script src="{% static "node_modules/bootstrap/dist/js/bootstrap.min.js" %}"></script>
<script src="{% static "bower_components/alertify.js/lib/alertify.min.js" %}"></script>
<!-- 1. Load libraries -->
<!-- Polyfill(s) for older browsers -->
<script src="{% static "node_modules/core-js/client/shim.min.js" %}"></script>
<script src="{% static "node_modules/zone.js/dist/zone.js" %}"></script>
<script src="{% static "node_modules/reflect-metadata/Reflect.js" %}"></script>
<script src="{% static "node_modules/systemjs/dist/system.src.js" %}"></script>
<!-- 2. Configure SystemJS -->
<script src="{% static "systemjs.config.js" %}"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
</head>
<!-- 3. Display the application -->
<body>
<photohub></photohub>
</body>
</html>
make changes in systemjs.config.js:
(function (global) {
System.config({
//static
defaultJSExtensions: true,
paths: {
// paths serve as alias
'npm:': 'static/node_modules/'
},
// map tells the System loader where to look for things
map: {
app: 'static/dist',
// angular bundles
'#angular/core': 'npm:#angular/core/bundles/core.umd.js',
'#angular/common': 'npm:#angular/common/bundles/common.umd.js',
'#angular/compiler': 'npm:#angular/compiler/bundles/compiler.umd.js',
'#angular/platform-browser': 'npm:#angular/platform-browser/bundles/platform-browser.umd.js',
'#angular/platform-browser-dynamic': 'npm:#angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'#angular/http': 'npm:#angular/http/bundles/http.umd.js',
'#angular/router': 'npm:#angular/router/bundles/router.umd.js',
'#angular/forms': 'npm:#angular/forms/bundles/forms.umd.js',
// other libraries
'rxjs': 'npm:rxjs',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api',
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: './main.js',
defaultExtension: 'js'
},
rxjs: {
defaultExtension: 'js'
},
'angular-in-memory-web-api': {
main: './index.js',
defaultExtension: 'js'
}
}
});
})(this);
The TypeScript files are compiled in /dist and templates remained in /app. When I used two different servers the path for templateUrl look like this:
templateUrl: './app/app.component.html'
now I'm trying to declare templateUrl this way, but it doesn't work:
templateUrl: '{{ STATIC_URL }}' + '/app/app.component.html'
How to deal with templates urls now?
Response:
"GET /app/components/login/login.component.html HTTP/1.1" 404 2601
Not Found: /app/app.component.html
JavaScript files loaded well:
"GET /app/components/login/login.component.html HTTP/1.1" 404 2601
Not Found: /app/components/register/register.component.html
This solved problem:
templateUrl: 'static/app/app.component.html'
I am not sure what error you're having but you probably should use the static tag to make a URL to a static asset in your template:
{% load static %}
templateUrl: "{% static '/app/app.component.html' %}"
Doc: https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#std:templatetag-static

Twitter bootstrap with Django 1.5

I am trying to integrate Twitter bootstrap with my django application. In settings.py, I have:
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
"/path/to/my/projects/templates/static/",
)
Under the static folder, there are 3 folders namely, css, img and js and all the bootstrap files have been copied into it as is.
My template looks like so:
<html>
<head>
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap-responsive.css' %}" />
<script type="text/javascript" src="{% static 'js/bootstrap.js' %}"></script>
<meta charset="utf-8">
<title>Test App</title>
</head>
<body>
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<ul class="nav">
<li class="active">
<a class="brand" href="#">TEST APP</a>
</li>
<li>About</li>
<li>Portfolio</li>
<li>Contact</li>
</ul>
</div>
</div>
</div>
How ever, when I run the development server, I get a basic html page with no change and no css applied.
What am I doing wrong here?
Assuming that your static folder is immediately underneath your Application root, this is a method that you could use to bullet-proof static file template rendering on all OSs.
import os
def replace(path):
assert isinstance(path, str)
return path.replace('\\', os.sep)
def here(*args):
return replace(os.path.abspath(os.path.join(os.path.dirname(__file__), *args)))
BASE_DIR = here('..')
def root(*args):
return replace(os.path.abspath(os.path.join(BASE_DIR, *args)))
STATICFILES_DIRS = (root('static'),)

Categories

Resources