Django-Compressor throws UncompressableFileError - django

I'm using django-compressor and django-staticfiles (the external version, I'm on Django 1.2).
When I try to load my site, I get an error:
TemplateSyntaxError: Caught UncompressableFileError while rendering: 'css/facebox.css' isn't accesible via COMPRESS_URL ('/static/') and can't be compressed
I've verified COMPRESS_URL is equal to STATIC_URL, and the file is actually accessible at that URL.
Looking at the django-compressor code, I found where that exception is thrown:
def get_basename(self, url):
try:
base_url = self.storage.base_url
except AttributeError:
base_url = settings.COMPRESS_URL
# I added the following print statement:
print "url: %s, base_url: %s" % (url, base_url)
if not url.startswith(base_url):
raise UncompressableFileError("'%s' isn't accesible via "
"COMPRESS_URL ('%s') and can't be "
"compressed" % (url, base_url))
The first {% compress css %} block in my templates is this:
{% compress css %}
<link rel="stylesheet" href="/static/css/blueprint/screen.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/facebox.css" />
{% endcompress %}
(Note that the first link doesn't use {{ STATIC_URL }}, but the second one does)
And I get this in my error log:
[Thu Oct 13 08:19:13 2011] [error] url: /static/css/blueprint/screen.css, base_url: /static/
[Thu Oct 13 08:19:13 2011] [error] url: /static/css/facebox.css, base_url: /static/
[Thu Oct 13 08:19:14 2011] [error] url: /static/css/blueprint/screen.css, base_url: /static/
[Thu Oct 13 08:19:14 2011] [error] url: css/facebox.css, base_url: /static/
As you can see, the screen.css file is processed twice, and successful the second time around. The facebox.css file, however, fails the second time, presumable because the {{ STATIC_URL }} isn't defined in the template context the second time the file is parsed.
Obviously I could solve the problem by not using {{ STATIC_URL }}, but that is not an acceptable solution.
Why would my css files be processed twice? They originally had media='screen, projection', but I removed that thinking it was causing the problem.
Relevant settings:
In [4]: from compressor.conf import settings
In [5]: settings.COMPRESS_ROOT
Out[5]: '/home/ianchat/static_files'
In [6]: settings.STATIC_ROOT
Out[6]: '/home/ianchat/static_files'
In [7]: settings.COMPRESS_URL
Out[7]: '/static/'
In [8]: settings.STATIC_URL
Out[8]: '/static/'
In [9]: settings.COMPRESS_OUTPUT_DIR
Out[9]: 'CACHE'
In [10]: settings.COMPRESS_CSS_FILTERS
Out[10]: ['compressor.filters.csstidy.CSSTidyFilter']
In [11]: settings.STATICFILES_FINDERS
Out[11]:
('staticfiles.finders.FileSystemFinder',
'staticfiles.finders.AppDirectoriesFinder',
'staticfiles.finders.LegacyAppDirectoriesFinder',
'compressor.finders.CompressorFinder')

I bumped into the same issue.
The answer was found here: https://github.com/jezdez/django_compressor/pull/206
The link's solution is doing handler500.
I decided to change 500.html template to avoid any {{STATIC_URL}} in it and the problem was solved.

It almost looks like STATIC_URL is not in your context. You do have the staticfiles contextprocessor configured, right? Have you tried to like the file without the compressor tags? Does {{ STATIC_URL }} show up correctly in the page when you load it?
I think compressor checks the url even if it accesses it through the file system looking at https://github.com/jezdez/django_compressor/blob/develop/compressor/base.py#L57

This is an old question, but one of the few search results when searching for this error message, so it might be worth someting to share my solution.
In my case it was a dead simple case: I hardcoded my static url and forgot the / at the beginning. So I had this:
<link type="text/css" rel="stylesheet" href="static/style.css" />
Which gave me the error. After changing to this:
<link type="text/css" rel="stylesheet" href="/static/style.css" />
It was fixed. Of course, I later realised, I should have used the setting STATIC_URL:
<link type="text/css" rel="stylesheet" href="{{ STATIC_URL }}style.css" />
Hope this helps anyone.

I've look at it some more and I'm pretty sure the exception is caused by trying to display an uncatched error page without the full context the first pass had. This causes the exception in django-compressor.[1]
The solution, of course, is to handle all errors.
[1] I'm also running some non-standard code to display static pages, maybe this interferes and the reason that the bug is not too common.

I ran into the same issue; in my case the problem was caused by using COMPRESS_OFFLINE_CONTEXT - which does not .update() the context but it replaces it altogether, thus removing STATIC_URL.
The solution in my case was just adding it back to the COMPRESS_OFFLINE_CONTEXT, after the local_settings import, otherwise any override there wouldn't have worked.

Related

Why is staticfiles not able to find or serve .css, using FORCE_SCRIPT_NAME in docker

EDIT/Workaround:
I got this working. I think there is an unfortunate interaction of FORCE_SCRIPT_NAME, the requirement for STATIC_URL to end in /, and the behavior of django.conf.urls.static. I'll mark this answered when I'm able to put together a step-by-step explanation.
Meanwhile, here's the recipe that works for me:
urls.py
from django.conf.urls.static import static
urlpatterns += static("static", document_root=settings.STATIC_ROOT)
settings.py
FORCE_SCRIPT_NAME = "/the-prefix-i-need/"
STATIC_ROOT = "/static/"
STATIC_URL = "static/"
STATIC_URL has to end with "/" (or runserver fails). But if static's first argument ends with / it pulls in the FORCE_SCRIPT_NAME into the URL pattern it is looking for, and doesn't match "/static"
In development (DEBUG=True) mode, running in docker on a host where the site is served with a prepended path corresponding to a branch, I am unable to get static files working.
Using python 4.0.6
In settings.py I have these settings:
DEBUG = True
BASE_DIR = Path(__file__).resolve().parent.parent # default generated
FORCE_SCRIPT_NAME = "https://pmdocker01d.pm.local:8443/bi-web-utils/ta0624/"
INSTALLED_APPS = [
...
'django.contrib.staticfiles',
STATIC_URL = 'static/'
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
In my html file:
{% load static %}
<html>
<head>
...
<link rel="stylesheet" href="{% static 'tableau_explorer/style.css' %}">
And my css is in:
django_root/tableau_explorer/static/tableau_explorer
On my development machine, both running manage.py from the sheel, and
in a dockerfile, it works. In that setting, I don't have FORCE_SCRIPT_NAME.
When it is on the other docker host, the generated HTML
<link rel="stylesheet" href="/static/tableau_explorer/style.css">
And I get a 404 error.
If I change:
STATIC_URL = 'https://pmdocker01d.pm.local:8443/bi-web-utils/ta0624/static/'
Then it instead of a plain 404 I get message that it's getting HTML instead of css, because the server is returning this
Request Method: GET
Request URL: http://https://pmdocker01d.pm.local:8443/bi-web-utils/ta0624/static/tableau_explorer/style.css
Using the URLconf defined in bi_web.urls, Django tried these URL patterns, in this order:
admin/
....
The current path, static/tableau_explorer/style.css, didn’t match any of these.
For the other docker host I tried adding this to the main project
urls.py (not tableau/explorer/urls.py) I tried adding this and and
couldn't see any difference:
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [ . . . . ]
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
If I browse to https://pmdocker01d.pm.local:8443/bi-web-utils/ta0624/static/
I get the error message "Directory indexes are not allowed here.", whereas
other urls like making it end "staticx/" it just says page not found. So
I think static is doing something, but I can't tell that anything at all is
being gathered there and don't know how to check.
If I make a shell connection into the running docker host, it seems like static
is finding what I'd expect:
$ python manage.py findstatic tableau_explorer/style.css
Found 'tableau_explorer/style.css' here:
/code/tableau_explorer/static/tableau_explorer/style.css
Anyone know right off what's going on and can tell me "type this and it'll work?"
If not...
My question now is - what is the staticfiles supposed to be doing with files
in development mode, and how does it serve them?
is it supposed to intercept any request that begins with "static/"
when the app starts running, does staticfiles gather the .css files from
different applications "static" folders, and put copies into an on-disk
repository I can verify, or put verbose logging on? -- Should I be able
to see the files in a particular directory on the running server?
is the BASE_DIR setting relevant to staticfiles? I am using what was
generated by manage.py createproject
in staticfiles nowadays, is it supposed to take care of appending "static" into
the urls? I thought I shouldn't need to modify urls.py?
-- Edit:
Since posting I added STATIC_ROOT=/static in the settings.py file, and in Dockerfile I added collectstatic. When I shell into the running docker image on the host I see
$ ls -l /static/tableau_explorer/style.css
The files are present good, and are other-accessible all the way down.
The rendered HTML file has
<link rel="stylesheet" href="https://pmdocker01d.pm.local:8443/bi-web-utils/ta0624/static/tableau_explorer/style.css">
and if I browse directly to that link, Django is complaining it doesn't match any path... I feel like I have to do something in urls.py to give the request to staticfiles to handle?
The response when I browse is the familiar:
<html lang="en"><head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Page not found at /static/tableau_explorer/style.css</title>
</head>
<body>
<div id="summary">
<h1>Page not found <span>(404)</span></h1>
<table class="meta">
<tbody><tr>
<th>Request Method:</th>
<td>GET</td>
</tr>
<tr>
<th>Request URL:</th>
<td>http://https://pmdocker01d.pm.local:8443/bi-web-utils/ta0624/static/tableau_explorer/style.css</td>
</tr>
</tbody></table>
</div>
<div id="info">
<p>
Using the URLconf defined in <code>bi_web.urls</code>,
Django tried these URL patterns, in this order:
</p>
<ol>
. . . . Nothing about "/static" . . .
</ol>
<p>
The current path, <code>static/tableau_explorer/style.css</code>,
didn’t match any of these.
</p>
....

Django cannot locate static files for the index page of the website

So, in my index page located in root/templates/home.html I have the following line for loading CSS:
<link rel="stylesheet" href="{% static 'project/home.css' %}">
home.css is located at: root/static/project/home.css
In settings.py:
STATIC_ROOT = "static/"
STATIC_URL = '/static/'
And when I run the server, in the main page CSS fails to load raising 404 in the browser although the browser displaying the correct path where the home.css is located:
http://127.0.0.1:8000/static/project/home.css
For all apps in the projects everything works fine.
When global static is defined in settings.py:
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
the problem is solved, but then, for obvious reasons I cannot perform collectstatic unless I rename it to "assets" for example.
I am clearly missing something here but I want to know why it fails to load the home.css from the legit path?

Django can't find the static files

I just started a new project and currently Django can't find the static files. I'm using Django==2.2.6
The static files are located in an app called "website". This is the file structure.
https://i.imgur.com/AnPACop.png
This is from the settings:
STATIC_URL = '/static/'
This is how i include the static file:
{% static 'css/style.css' %}
The URL to the static file seems correct:
<link href="/static/css/style.css" rel="stylesheet">
EDIT: its NOT correct. But this works:
<link href="/static/core/css/style.css" rel="stylesheet">
Make your file structure like the following one:
ProjectFolderName
static
- css
- js
template
website
projectfoldername
migrations
Put your static folder in your project folder. Then make these changes to your settings.py:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
Then run this command:
python manage.py collectstatic
You static file will be copied to New file created by django as assets.
and add to your HTML
{% load static %}
This is the URL that the browser will find your static files. It won't let Django know in which folder to find them inside your project root (`BASE_DIR)
STATIC_URL = '/static/'
Try using this instead to specify the directory you are storing the statics
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'website/static'),)
Also, make sure you are loading the statics in your template with the following template tag
{% load static %}
Update
The path to the CSS is also wrong on the html you should change it to:
<link href="/static/core/css/style.css" rel="stylesheet">
It's solved. The problem was the file structure. For some reason the static files was in a core-folder.
https://i.imgur.com/AnPACop.png
When i put the files directly in "static" it started working.
My english is not perfect, sorry in advance.
I'm in Django 3 and I had the same problem. This how I find what's wrong, with the help of everyone up me. Just consider this post like a note for me.
I do :
python3 manage.py runserver
At this moment I read the last line of the output. It was looking in a file that did'nt exist. I copied the path. Go in terminal and :
cd path/copied/before/static/base.css
File not found. At this moment I know what to do. Just follow the path and create the folder I need.
I know it's not a good practise but it's can help beginner.

Django Appending Slashes to Static File URLs on OpenShift

I am attempting to deploy a Django 1.6 application on OpenShift using the Python 3.3 cartridge, but I have run into problems with static files. I have had partial success with the OpenShift IRC channel, tutorials/templates (for example), and previous StackExchange questions (for example), but nothing has completely resolved the problem.
When I request the static content by URL (e.g. 'mydomain.com/static/stylesheet.css' or 'mydomain.com/static/icons/cog.svg') I can see them perfectly fine. When static files are used as SVG data for icons, they show up fine. Only when linking to a stylesheet have I run into problems. I use the following to include CSS in my template:
<link type="text/css" rel="stylesheet" href={% static "stylesheet.css" %}/>
I have loaded the static files tag set with {% load staticfiles %}. Instead of seeing the stylesheet at /static/stylesheet.css, Django (I assume that it is Django, not Apache) looks for it at /static/stylesheet.css/ (note the trailing slash). This causes the request to fail with a 404 status code. The same thing occurs when I use other file extensions (I have tried .txt, .css, and .svg) or link to a file contained in a subdirectory of static. It is only in this circumstance that an extra trailing slash is appended.
It is my understanding that Django appends a trailing slash to a URL in the event that the URL does not match any of the patterns defined in urls.py. Is it possible on OpenShift to configure Apache so that it directly handles all requests to URLs of the form /static/*? I have an .htaccess file in the wsgi directory with the commands
Rewrite Engine On
Rewrite Rule ^application/static/(.+)$ /static/$1 [L]
but this does not solve the problem. I have also tried using a rewrite rule for just the stylesheet as well as a few things with Alias but have had no luck there, either.
Should Django be getting the requests for these static files at all? I have confirmed that DEBUG is being set to False in my settings.py file, and make no mention of django.views.static.serve in my urls.py file. Here are the relevant parts of settings.py:
STATIC_URL = '/static/'
if 'OPENSHIFT_REPO_DIR' in os.environ:
STATIC_ROOT = os.path.join(os.environ.get('OPENSHIFT_REPO_DIR'),
'wsgi', 'static')
else:
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
I do not set values for STATICFILES_DIRS or STATICFILES_FINDERS because at present I'm only dealing with static files found at STATIC_ROOT. The OpenShift project looks like
~/app-root/runtime/repo/wsgi/
.htaccess
application
openshift/
settings.py
manage.py
#And so on.
static/
stylesheet.css
icons/
cog.svg
#More icons here.
This is my first time trying to deploy and I am stuck on this stumbling block. Does anyone know what I am doing wrong?
Instead of href={% static "stylesheet.css" %}, try href="{% static 'stylesheet.css' %}"

Pycharm + Django 1.3 + STATIC_URL in templates = Unresolved static reference

PyCharm (1.3 and 2 beta) in my Django 1.3 project throws a lot of "unresolved static reference" errors when inspecting my templates for script and style includes.
In an outdated PyCharm doc, I found that a small guide that doesn't work in my situation, because my static files are spread over multiple apps. Adding my static dirs to STATICFILES_DIRS also didn't work.
Dir structure (simplified):
app1/static/js/file.js
app1/static/css/file.css
app2/static/js/otherfile.js
app2/static/css/otherfile.css
templates/template.html
­
Template.html:
<script src="{{ STATIC_URL }}js/file.js"></script>
file.js resolves when I visit the template on localhost, but not in PyCharm.
How do I make static files resolve in PyCharm?
Go to Settings in Pycharm 2.73
Settings >> Project Setting >> Django
Enable the Django support and provide the paths for the three following files:
Project Root
Settings file
Manage.py file
When you have given these informations, close PyCharm and restart it.
PyCharm 2.5 finds my static files again.
The trick is to mark app1/static and app2/static as "Source Root".
STATICFILES_DIRS is not working for me.
The selected answer doesn't work for me. What solved it is using a prefix in STATICFILES_DIRS:
STATICFILES_DIRS = (
# ...
("resources", "C:/data/django/myproject/myapp/static"), )
as documented in the django docs: https://docs.djangoproject.com/en/1.4/ref/contrib/staticfiles/
Then in your html template:
<link rel="stylesheet" href="{%static 'resources/favicon.png' %}" type="text/css">
STATICFILES_DIRS works for
{% static "js/lib/jquery-1.8.2.min.js" %}
tag in template.
Not for {{ STATIC_URL }}js/lib/jquery-1.8.2.min.js
http://youtrack.jetbrains.com/issue/PY-5568