Static files doesn't load anymore - Django - django

In the beginning everything worked perfectly fine, but now I have a problem where my static files doesn't load. I think this is a very weird problem since I didn't really touch anything that could've had an influence on the problem when it happened. Everything else is working fine, I just can't get the static files for some reason. I sometimes get a 200 http response trying to get the static files like so:
[20/Aug/2020 16:12:51] "GET /order/checkout/ HTTP/1.1" 200 2029
[20/Aug/2020 16:12:51] "GET /static/my_pizza_place/js/client.js HTTP/1.1" 200 2194
[20/Aug/2020 16:12:51] "GET /static/css/master.css HTTP/1.1" 200 80
[20/Aug/2020 16:12:51] "GET /static/css/global.css HTTP/1.1" 200 530
But it's still not applying the styling to my html code. I usually just get a 304 http response on my client.js file though. I feel like I have tried almost everything at this point, so I hope you guys can help me figuring out what the problem is.
My files:
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')]
BASE.HTML
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
...
<link rel="stylesheet" href="{% static 'css/master.css' %}">
<link rel="stylesheet" href="{% static 'css/global.css' %}">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="..." crossorigin="anonymous">
<script src="{% static 'my_pizza_place/js/client.js' %}" defer></script>
</head>
<body>
<div class="container mycontent">
{% block checkout %}
{% endblock %}
</div>
</body>
</html>
INDEX.HTML
{% extends 'base.html' %}
{% block content %}
...
{% endblock %}
URLS.PY - IN PROJECT FOLDER
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.HomePage.as_view(),name="home"),
path('customer/',include('customer.urls', namespace='customer')),
path('customer/',include('django.contrib.auth.urls')),
path('order/',include('orders.urls',namespace='order'))
]
VIEWS.PY
class HomePage(TemplateView):
template_name = 'index.html'
DIRECTORY STRUCTURE
Project
app_name
project_name
static
css
global.css
master.css
my_pizza_place
js
client.js
templates
base.html
If you need any more information please just ask. Thanks in advance

Your problem is simply that you should add {% load static %} in each file. You don't have to necessarily link the css files in each .html file, but in each file you should load the static files. I have faced this problem before and I am sure this will solve it for you, be sure to add the {% load static %} before the {%block content %} tag. If you need further explanation, comment below.

Related

Why is Django template not responding to static files?

It is exactly how it sounds. My main goal is to make the css file work with django template so I can design my templates.
Yesterday I tried and initially my folder structure was wrong. I placed static folder in myapp folder. Didn't work. I tried putting it in templates folder. It only worked when I had 2 static folders both in myapp and templates folder. Realized it isn't a working solution.
I placed a single static folder with a css file in it in mysite folder, at the same level with myapp folder and everything seemed to work. Satisfied I left at that.
Today I came back to it and it stopped working. It seems to be frozen. Not responding to the new codes. Old colors are showing but new colors aren't, which is odd. Tried changing the old colors, it won't change. Literally my css file has a class name .intro where I changed the color from purple to red, my template still showing purple which I set yesterday.
My template shows no error and all the texts and divs I am adding are updating with no issue.Kind of lost where I may have gone wrong. Certainly don't want to work with 2/3 same css file and static folder if I can help it.
Here are some codes.
My folder structure-
Everytime I update the css and refresh the template my console is showing some kind of error, here they are-
Settings.py file seems correct. Here is the relevant part-
import os
SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__))
...
...
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR,'static'),
)
STATIC_ROOT= os.path.join(BASE_DIR, 'staticfiles')
my base.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>
<link rel="stylesheet" type="text/css" href="{% static 'ok.css' %}"/>
</head>
<body>
{% block content %}
<h2 class="ok">This is a test</h2>
<div class="solved">This took a while!</div>
<div class="container">Didn't work on the other site!</div>
{% endblock content %}
</body>
</html>
and test.html -
{% extends "myapp/base.html" %}
{% block content %}
<h2 class="again">Content for My App</h2>
<p class="intro">Stuff etc etc.</p>
<p class="ok">write some more</p>
<div class="container">This should work</div>
{% endblock %}
URLs.py even though I think I am doing ok there -
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('base/', views.ok, name='base'),
path('test/', views.test, name='test')
]
And finally views.py , another page I don't think have any issues -
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
context = {}
return render(request, 'myapp/index.html')
def ok(request):
return render(request, 'myapp/base.html')
def test(request):
return render(request, 'myapp/test.html')
If you can spot anything kindly let me know. Any help is appreciated. Thanks.

Using user CSS sheet in a template

I'm using Django to display user uploaded static HTML and CSS files. The HTML isn't a problem, however I can't get Django to actually render using the uploaded CSS.
Project structure is the following:
my_project
main_app
display_app
my_project
media
user
whatever.html
whatver.css
My main url.py contains:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^html_uploads/', include('display_app.urls')),
url(r'^', include('main_app.urls')),] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
display_app urls.py is:
urlpatterns = [
url(r'^(?P<requested>(?:[\w]+\/?)+)$', views.readhtml, name='requested'),]
The relevant part of the view is:
def read_html(request, file_name):
title = 'html_file_title'
body = get_body(file_name)
css_source = 'user/whatever.css'
return render(request, "display_app/base.html",
{'title': title,
'body': body,
'css_source': css_source,
'media_url': settings.MEDIA_URL,}
)
The CSS simply contains:
body {
background-color: #FFCC66
}
And the template looks like:
<head>
<title>{{ title }}</title>
<link rel="stylesheet" href="{{ media_url }}{{ css_source }}" type="text/css" />
</head>
<body>
{% autoescape off %}
{{ body }}
{% endautoescape %}
</body>
With this, I get a 404 as Django fails to find /media/user/whatever.css.
If I change the CSS location to:
<link rel="stylesheet" href="/{{ media_url }}{{ css_source }}" type="text/css" />
The 404 warning disappears, the HTML still loads, however the CSS is silently ignored.
The HTML is passed through several functions and heavily modified, therefore passing it as a string made sense, however the CSS should be used directly and I was hoping to load it from the template instead.
What's going on there? Does not getting a 404 warning mean Django is locating the CSS file correctly? If it is, why is it not used?

Django not finding some JS and CSS resources

Perhaps this is a laughable problem but am really lost. It was working fine until I ported the project to a new laptop. Here is my filesystem structure:
bill
==>bill (contains settings.py)
==>static
==>welcome
==>manage.py
Now in static i have my directory, i have folder plugins, js and css. The following are in my base.html template:
<!DOCTYPE html>
{% load staticfiles %}
<html lang="en">
<head>
<title>{% block ownername %}{% endblock %} {% block title %}{% endblock %}</title>
<script src="{% static 'plugins/jQuery/jquery-2.2.3.min.js' %}"></script>
<!-- Bootstrap 3.3.6 -->
<link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'plugins/datepicker/datepicker3.css' %}">
**<link rel="stylesheet" href="{% static 'plugins/lobibox/lobibox.min.css' %}">**
<script src="{% static 'plugins/slimScroll/jquery.slimscroll.min.js' %}"></script>
**<script src="{% static 'plugins/moments/moment.min.js' %}"></script>**
It loads some resources while it gives 404 for some other resources that are there and working in my old laptop (the bold ones such as moment.min.js and css files). The configuration is the same since I used virtual environment to start it.
What am I missing please? I am really lost on what it is doing.
No question is laughable :)
To begin with, change {% load staticfiles %} to {% load static %}.
Then make sure you've got the correct settings in terms of static files. A good setup would look like this:
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = '/static/'
If you are running your app without DEBUG=True, then also run python manage.py collectstatic --no-input from your terminal - that should do the trick to serve static assets in prod environment.
Try it and let us know how it went.

Django Static wont Load

I am learning how to use django but having difficulties using static files.
Files (BASE_DIR is website, App is player):
Website
└─── player
└─── static
└─── style.css
└─── admin
In Settings:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'player/static')
In index.html:
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{ static 'style.css' %}" >
In style.css:
body {
background-color: blue
}
I have ran collectstatic.
When loaded, the HTML appears without the css.
The console reads:
[23/Nov/2016 23:33:13] "GET / HTTP/1.1" 200 278
Not Found: /{ static 'style.css' %}
[23/Nov/2016 23:33:13] "GET /%7B%20static%20'style.css'%20%%7D HTTP/1.1" 404 2172
Did you run the python manage.py collectstatic?
Wrong directive in template:
{% load static %}
should be
{% load staticfiles %}
Update
also not:
{ static 'style.css' %}
but
{% static 'style.css' %}
Basic spelling errors

How can I get a favicon to show up in my django app?

I just want to drop the favicon.ico in my staticfiles directory and then have it show up in my app.
How can I accomplish this?
I have placed the favicon.ico file in my staticfiles directory, but it doesn't show up and I see this in my log:
127.0.0.1 - - [21/Feb/2014 10:10:53] "GET /favicon.ico HTTP/1.1" 404 -
If I go to http://localhost:8000/static/favicon.ico, I can see the favicon.
If you have a base or header template that's included everywhere why not include the favicon there with basic HTML?
<link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}"/>
One lightweight trick is to make a redirect in your urls.py file, e.g. add a view like so:
from django.views.generic.base import RedirectView
favicon_view = RedirectView.as_view(url='/static/favicon.ico', permanent=True)
urlpatterns = [
...
re_path(r'^favicon\.ico$', favicon_view),
...
]
This works well as an easy trick for getting favicons working when you don't really have other static content to host.
In template file
{% load static %}
Then within <head> tag
<link rel="shortcut icon" href="{% static 'favicon.ico' %}">
This assumes that you have static files configured appropiately in settings.py.
Note: older versions of Django use load staticfiles, not load static.
Universal solution
You can get the favicon showing up in Django the same way you can do in any other framework: just use pure HTML.
Add the following code to the header of your HTML template.
Better, to your base HTML template if the favicon is the same across your application.
<link rel="shortcut icon" href="{% static 'favicon/favicon.png' %}"/>
The previous code assumes:
You have a folder named 'favicon' in your static folder
The favicon file has the name 'favicon.png'
You have properly set the setting variable STATIC_URL
You can find useful information about file format support and how to use favicons in this article of Wikipedia https://en.wikipedia.org/wiki/Favicon.
I can recommend use .png for universal browser compatibility.
EDIT:
As posted in one comment,
"Don't forget to add {% load staticfiles %} in top of your template file!"
In your settings.py add a root staticfiles directory:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
Create /static/images/favicon.ico
Add the favicon to your template(base.html):
{% load static %}
<link rel="shortcut icon" type="image/png" href="{% static 'images/favicon.ico' %}"/>
And create a url redirect in urls.py because browsers look for a favicon in /favicon.ico
from django.contrib.staticfiles.storage import staticfiles_storage
from django.views.generic.base import RedirectView
urlpatterns = [
...
path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url('images/favicon.ico')))
]
<link rel="shortcut icon" href="{% static 'favicon/favicon.ico' %}"/>
Just add that in ur base file like first answer but ico extension and add it to the static folder
First
Upload your favicon.ico to your app static path, or the path you configured by STATICFILES_DIRS in settings.py
Second
In app base template file:
{% load static %}
<link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}"/>
You can make apps use different favicon.ico files here.
Addition
In project/urls.py
from django.templatetags.static import static # Not from django.conf.urls.static
from django.views.generic.base import RedirectView
Add this path to your urlpatterns base location
path('favicon.ico', RedirectView.as_view(url=static('favicon.ico'))),
This can let installed app(like admin, which you should not change the templates) and the app you forget modify the templates , also show a default favicon.ico
if you have permission then
Alias /favicon.ico /var/www/aktel/workspace1/PyBot/PyBot/static/favicon.ico
add alias to your virtual host. (in apache config file ) similarly for robots.txt
Alias /robots.txt /var/www/---your path ---/PyBot/robots.txt
I tried the following settings in django 2.1.1
base.html
<head>
{% load static %}
<link rel="shortcut icon" type="image/png" href="{% static 'images/favicon.ico' %}"/>
</head>
settings.py
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'` <br>`.............
Project directory structure
view live here
<link rel="shortcut icon" type="image/png" href="{% static 'favicon/sample.png' %}" />
Also run: python manage.py collectstatic
The best solution is to override the Django base.html template. Make another base.html template under admin directory. Make an admin directory first if it does not exist. app/admin/base.html.
Add {% block extrahead %} to the overriding template.
{% extends 'admin/base.html' %}
{% load staticfiles %}
{% block javascripts %}
{{ block.super }}
<script type="text/javascript" src="{% static 'app/js/action.js' %}"></script>
{% endblock %}
{% block extrahead %}
<link rel="shortcut icon" href="{% static 'app/img/favicon.ico' %}" />
{% endblock %}
{% block stylesheets %}
{{ block.super }}
{% endblock %}
Came across this while looking for help. I was trying to implement the favicon in my Django project and it was not showing -- wanted to add to the conversation.
While trying to implement the favicon in my Django project I renamed the 'favicon.ico' file to 'my_filename.ico' –– the image would not show. After renaming to 'favicon.ico' resolved the issue and graphic displayed. below is the code that resolved my issue:
<link rel="shortcut icon" type="image/png" href="{% static 'img/favicon.ico' %}" />
Best practices :
Contrary to what you may think, the favicon can be of any size and of any image type. Follow this link for details.
Not putting a link to your favicon can slow down the page load.
In a django project, suppose the path to your favicon is :
myapp/static/icons/favicon.png
in your django templates (preferably in the base template), add this line to head of the page :
<link rel="shortcut icon" href="{% static 'icons/favicon.png' %}">
Note :
We suppose, the static settings are well configured in settings.py.
Just copy your favicon on:
/yourappname/mainapp(ex:core)/static/mainapp(ex:core)/img
Then go to your mainapp template(ex:base.html)
and just copy this, after {% load static %} because you must load first the statics.
<link href="{% static 'core/img/favi_x.png' %}" rel="shortcut icon" type="image/png" />
Now(in 2020),
You could add a base tag in html file.
<head>
<base href="https://www.example.com/static/">
</head>
Sometimes restarting the server helps.
Stop the server and then rerun the command: python manage.py runserver
Now your CSS file should be loaded.