Using user CSS sheet in a template - django

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?

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.

Static files doesn't load anymore - 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.

CSS not applying to HTML page when receiving a new render in Django

I am currently struggling on a problem of HTML response.
I have an HTML page with CSS,JS working fine, the user will do an interaction that will go to JS -> send ajax request and do some treatment within a working view. And this view give me back a rendered view with all the info updated.
The problem is that the HTML given is containing everything but looks like "raw" HTML a.k.a no CSS applied to it, (scripts are working fine)
In the head of my HTML file :
<head>
<meta charset="utf-8">
<title>Sorting video: {{video.title}}</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="https://www.w3schools.com/w3css/4/w3.css">
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'modelReco/cssFiles/swipeFrames.css' %}?v=00002'">
<script type="text/javascript" src='{% static "modelReco/jsScript/swipeFrames.js" %}?v=00003'></script>
</head>
The view that render the HTML:
def sendSortVideoResponse(request,untreatedFrame,myVideo,frames,tracks,url):
response = render(request, url, {
'video':myVideo,
'frames':frames,
'tracks':tracks,
'untreatedFrame': untreatedFrame[0],
'countTreated': untreatedFrame[1],
'totalFrames': len(frames),
'progressBar': untreatedFrame[1]/len(frames)*100,
})
response["Cache-Control"] = "no-cache, no-store, must-revalidate"
response["Pragma"] = "no-cache" # HTTP 1.0.
response["Expires"] = "0" # Proxies.
return response
In settings.py :
PROJECT_ROOT = os.path.join(os.path.dirname(__file__), '..')
SITE_ROOT = PROJECT_ROOT
MEDIA_ROOT = os.path.join(SITE_ROOT, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
STATIC_URL = '/static/'
If you F5 the page then everything works fine again.
For the user, the page he is on doesn't reload so it might be the problem but I have an other stylesheet doing a progressing bar working perfectly so I'm confused.
So it might be a bad use of static files
EDIT Network and page :
Before the interaction :
After the interaction :
EDIT 2 : The rendered HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sorting video: fashionShow2</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" type="text/css" href="/static/modelReco/cssFiles/swipeFrames.css?v=00002'">
<script type="text/javascript" src='/static/modelReco/jsScript/swipeFrames.js?v=00003'></script>
</head>
<body>
<h1>Video: fashionShow2</h1>
<p>What can you do on this page?</p>
<p>You've chosen to sort the video fashionShow2, this means you want to help the A.I to recognize the model by simply clicking on the models and validate your answer</p>
<div id = 7951 class = "untreatedFrame" style="zoom:.6;-o-transform: scale(.6);-moz-transform: scale(.6)" >
<img class = "frameImg" src="/media/fashionShow2/frames/7951.png"/>
<a class = "frameImg" style="top: 0%; left: 65%; width: 35%; height: 100%;" onmouseover="displayValidation('rightCorner',true)" onmouseout="displayValidation('rightCorner',false)" onclick="validateFrameChoice(7951,1,true,'/modelReco/sortedTracks')">
<div id="rightCorner" class = "validationCorner"></div>
</a>
<a class = "frameImg" style="top: 0%; left: 0%; width: 35%; height: 100%;" onmouseover="displayValidation('leftCorner',true),true" onmouseout="displayValidation('leftCorner',false)" onclick="validateFrameChoice(7951,-1,false,'/modelReco/sortedTracks')">
<div id="leftCorner" class = "validationCorner"></div>
</a>
</div>
<div class="w3-container">
<div class="w3-light-grey w3-round-xlarge">
<div class="w3-container w3-blue w3-round-xlarge" style="width:73.01587301587301%">46/63</div>
</div>
</div>
<input type="button" value="Cancel previous choice" onclick="cancelPreviousChoice(7951)" />
<form action="/modelReco/">
<input type="submit" value="Return to home" />
</form>
<script>
</script>
</body>
</html>
settings.py
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
urls.py (project not app)
from django.conf import settings
from django.conf.urls.static import static
...
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
I found the issue on this problem. If you are trying to use ajax and render a new HTML by simply replacing everything with Jquery like I did ($("*").html(data);).
Be careful about applying CSS on your body element because browsers (as it is said on this post) usually don't care about those tags and remove it.
That's why in my retrieved ajax data, I had the body and everything but when rendered by the browser, the body tag was just disappearing.
If you need to apply CSS tags to body, just add a div tag like this and apply your css on it :
<body>
<div id="body">
....
</div>
</body>
The only weird thing is that when you F5 the page with Django the body tag come back, so the first look was ok but when rendered without refresh no body tag was showing.

Django- Staticfiles 404 on runserver

I'm not doing anything fancy. Just trying to get my static files to work using python manage.py runserver with Debug = True
'django.contrib.staticfiles' is installed.
These are my static settings:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
Here is my template syntax:
{% load staticfiles %}
<title>Dashboard</title>
<!-- Bootstrap Core CSS -->
<link href="{% static "boostrap/bower_components/bootstrap/dist/css/bootstrap.min.css" %}"
rel="stylesheet">
<!-- MetisMenu CSS -->
<link href="{% static "boostrap/bower_components/metisMenu/dist/metisMenu.min.css" %}"
rel="stylesheet">
<!-- Timeline CSS -->
<link href="{% static "boostrap/dist/css/timeline.css" %}" rel="stylesheet">
<!-- Custom CSS -->
<link href="{% static "boostrap/dist/css/sb-admin-2.css" %}" rel="stylesheet">
<!-- Morris Charts CSS -->
<link href="{% static "boostrap/bower_components/morrisjs/morris.css" %}" rel="stylesheet">
<!-- Custom Fonts -->
<link href="
{% static "boostrap/bower_components/font-awesome/css/font-awesome.min.css" %}" rel="stylesheet" type="text/css">
findstatic can successfully locate these files when entered exactly as they are in the template:
(AlmondKing) C:\Projects\AlmondKing>python manage.py findstatic bootstrap/bower_components/bootstrap/dist/css/bootstrap.min.css --verbosity 2
Found 'bootstrap/bower_components/bootstrap/dist/css/bootstrap.min.css' here:
C:\Projects\AlmondKing\AlmondKing\static\bootstrap\bower_components\bootstrap\dist\css\bootstrap.min.css
Looking in the following locations:
C:\Projects\AlmondKing\AlmondKing\static
C:\Users\Adam\Envs\AlmondKing\lib\site-packages\django\contrib\admin\static
My URLS have no conflict:
ROOT URLS:
urlpatterns = [
url(r'^', include('AlmondKing.AKGenius.urls', namespace="AKGenius")),
url(r'^admin/', include(admin.site.urls)),
url(r'^purchases/', include('AlmondKing.InventoryLogs.urls', namespace="purchases")),
url(r'^company/', include('AlmondKing.FinancialLogs.urls',namespace="company")),
]
AKGenius URLS:
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='home.html'), name="home"),
url(r'^dashboard/$', TemplateView.as_view(template_name='control_panel.html'), name="dashboard"),
url(r'^support/$', 'AlmondKing.AKGenius.views.support'),
]
and the paths seem to be rendering correctly to the browser:
<!-- Bootstrap Core CSS -->
<link href="/static/boostrap/bower_components/bootstrap/dist/css/bootstrap.min.css"
rel="stylesheet">
And yes, I've restarted runserver since my last settings change.
What could be causing these to 404? Would it have something to do with Windows?
And as a proper answer in case anybody else comes across this post at a later date:
Looks like there's a typo in each line, where
{% static "boostrap
should be
{% static "bootstrap

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.