Im working on a personal project and im using django.
In this project I like to use scss/sass style file, but I dont know how to install and set up in my Django project.
Any help will be appreciated
Thank u!
In order to work with scss or sass in django project
Step 1:
Install sass/scss in your local machine either npm or Homebrew (i prefer npm)
sass installation guide
Step 2:
After installation, you need to compile your sass/scss to css file.
For that, run the command (in cmd for windows)
sass [your scss file location] [where your css file needs to be stored]
For example..
sass source/stylesheets/index.scss build/stylesheets/index.css
If you are using django, then you must be using static folder in your project, in that case you should go with this command
sass static/scss/index.scss static/css/index.css
Step 3:
The above command needs to be executed every single time when a change occurs in scss file..
Inorder to get rid of that, use a --watch command.
sass --watch static/scss/index.scss static/css/index.css
There are more ways to do this. You can work with scss/sass files with Python or with NPM. If you do not want to mess with node.js I would recommend to use python way (install django-sass-processor):
Check out this clear manual - How to Easily Use SASS/SCSS with Django from webarchive or django-sass-processor.
Basically run install:
pip install libsass django-compressor django-sass-processor
Add to configuration file:
INSTALLED_APPS = [
...
'sass_processor',
...
]
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'sass_processor.finders.CssFinder',
]
STATIC_ROOT = BASE_DIR / 'static'
SASS_PROCESSOR_ROOT = STATIC_ROOT
Using Django-sass-processor in Templates:
Inside of your template, load in django-sass’s library tags and use {% sass_src %} instead of {% static %} to load your SCSS/SASS stylesheet.
{% load sass_tags %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="{% sass_src 'path/to/file.scss' %}" rel="stylesheet" type="text/css" />
<title>Django Sass</title>
</head>
<body>
<h1>This template's stylesheet was written SASS/SCSS</h1>
</body>
</html>
Related
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>
....
I'm trying to link a css stylesheet to my django html template but it keeps being read as an html file with the error:
127.0.0.1/:1 Refused to apply style from 'http://127.0.0.1:8000/static_cdn/css/base-template.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
This is my base.html file and I know the path is correct because VS Code directs me to the file when I left-click on the link.
<head>
<link type="text/css" rel="stylesheet" href="../../static_cdn/css/base-template.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>GuitarShop</title>
</head>
Here is my directory:
Project Folder
guitarshop > templates > base.html
static_cdn > css > base-template.css
The reason why I am storing the css file in the static_cdn folder instead of a static folder in the templates folder is because when I do so, the command "python manage.py collectstatic" doesn't collect the file folder so I get the following error:
GET http://127.0.0.1:8000/static/base-template.css net::ERR_ABORTED 404 (Not Found)
Please help!
Have you pointed your "Static_URL" to static_cdn folder?
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.
I'm been using Django Compressor to manage my coffee/less files and its great for development, but I've had some issues to make it work for my production deployment.
My idea is to have apache to host the static files, possibly in another server. I'm setting COMPRESS_OFFLINE = True on the settings.py file.
Then I do the following
python manage.py compress - This populates the CACHE directory in my static directory, where all static files will be collected.
python manage.py collectstatic - This collects static files from all the apps on my project (some of which don't use compressor) into my static directory.
Copy the static directory somewhere to be hosted with apache. And setup apache to serve the files.
Modify the static_url variable in the settings.py file to point to the static server.
If I open any page, I get the following error on my server, this only seems to happen when I have DEBUG = False and COMPRESS_OFFLINE = True on my settings.py file:
TemplateSyntaxError: Caught OfflineGenerationError while rendering:
You have offline compression enabled but key
"777ba26736d046ab043dc151e7e9a060" is missing from offline manifest.
You may need to run "python manage.py compress".
When I check the static/CACHE directory, I confirm what the error says, this is my manifest.json file:
{
"6189b8598993d1cbdbd35d4dfd1a6711": "<script type=\"text/javascript\" src=\"http://192.168.1.123/CACHE/js/2f6ca6616bd6.js\"></script>",
"5c66dbed0e5b766c6e32773cd8585f3c": "<link rel=\"stylesheet\" href=\"http://192.168.1.123/CACHE/css/154d95903951.css\" type=\"text/css\" />"
}
If I delete the CACHE directory and rerun python manage.py compress, I get a new set of ID's both on the error message and the manifest file, but the ID on the error is still missing on the manifest.
So, I guess there are two questions here. Why is it not working? What is the proper way to achieve this?
Thanks.
If you've run compress, and you still get the message
OfflineGenerationError: You have offline compression enabled but key "4971a40e3b459a8cda8287a7f7caa96d" is missing from offline manifest. You may need to run "python manage.py compress"
then it's likely you have dynamic content inside compress tags. Make sure that compress is always the innermost block, and that there are no tags inside the compress block.
I guess you're using django-compressor 1.1.2 which doesn't support static template tag {% static "..." %}.
Try installing the dev version of django-compressor with:
pip install django_compressor==dev
It should solve the problem.
David Wolfe is absolutely right: had to dig throught all the code of mine to get rid of {% trans... etc.
I make it like this:
<script>
window.__enter_email = "{% trans "Enter correct email" %}"
window.__url = "{% url "shop:go" %}"
</script>
{% compress js %}
<script>
$("#bla")..... window.__enter_email ...
</script>
{% endcompress %}
Hope, helps someone!
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