I'm running django 1.3, python 2.7 on windows XP
I'm trying to setup a css in a static folder for my django app.
The template looks like:
<html>
<head>
<title>css demo</title>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/my.css" />
</head>
<body>
The generated HTML looks like:
<html>
<head>
<title>css demo</title>
<link rel="stylesheet" type="text/css" href="http://localhost/static/css/my.css" />
</head>
...
So it appears that I have everything set up in order to specify where the static files are in the template, and then in the generated html.
But there is noting at 'http://localhost/static/css/my.css'. How do I get it there?
I ran collectstatic like so:
C:\root\workspace\mywebapp\src\mywebapp>c:\Python27\python.exe manage.py collectstatic
You have requested to collect static files at the destination location as specified in your settings file.
This will overwrite existing files.
Are you sure you want to do this?
Type 'yes' to continue, or 'no' to cancel: yes
Copying 'c:\root\workspace\mywebapp\src\mywebapp\css_demo\static\css\my.css'
1 static file copied to 'C:/root/workspace/mywebapp/src/mywebapp/static/'.
So I now have my.css in c:\root\workspace\mywebapp\src\mywebapp\css_demo\static\css\my.css
In my settings, I have:
STATIC_ROOT = 'C:/root/workspace/mywebapp/src/mywebapp/static/'
STATIC_URL = 'http://localhost/static/'
and in my url.py I have:
from django.conf.urls.defaults import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = patterns('',
(r'^mywebapp/', include('mywebapp.css_demo.urls')),
)
urlpatterns += staticfiles_urlpatterns()
So if I understand correctly, my css at:
c:\root\workspace\mywebapp\src\mywebapp\css_demo\static\css\my.css
should no be available at:
http://localhost/static/css/my.css
But instead I see:
Page not found (404)
Request Method: GET
Request URL: http://localhost/static/css/my.css
Using the URLconf defined in mywebapp.urls, Django tried these URL patterns, in this order:
^mywebapp/
The current URL, static/css/my.css, didn't match any of these.
I also tried:
http://localhost/mywebapp/static/css/my.css
http://localhost/mywebapp/css_demo/static/css/my.css
Am I missing a step here?
The documentation on this is a bit confusing.
http://docs.djangoproject.com/en/1.3/howto/static-files/
http://docs.djangoproject.com/en/1.3/ref/contrib/staticfiles/
Thanks!
I bet you have your app running at http://localhost:8000, not http://localhost :)
Change
STATIC_URL = 'http://localhost/static/'
to
STATIC_URL = '/static/'
No need for absolute URL there.
I created a folder:
C:\root\workspace\mysite\src\mysite\common
And in my settings, I have:
STATIC_ROOT = 'C:/root/workspace/mysite/src/mysite/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
"C:/root/workspace/mysite/src/mysite/common/static",
)
This seems to work.
Related
For a long time I tried to solve the problem with loading all my static files. When I found a working solution, all svg started loading, but css files didn't.
Here is my settings.py (showing you only main things)
import mimetypes
mimetypes.add_type("text/css", ".css", True)
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = False
STATIC_URL = '/static/'
if DEBUG: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
else: STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Here is my urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
from django.conf import settings
from django.views.static import serve
urlpatterns = [
path('', include('main.urls')),
url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),
]
Here is an example of using css files in my templates
{% load static %}
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-v4-grid-only#1.0.0/dist/bootstrap-grid.min.css">
<link rel="stylesheet" type="text/css" href=" {% static 'css/reset.css' %}">
<link rel="stylesheet" type="text/css" href=" {% static 'css/main.css' %}">
And this is the error in Chrome Console
Refused to apply style from '<URL>' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
And also i cant open css files in a new tab. I am getting that error
Also, if you remove %20 from the address bar, then I will open the css file
P.S.
I am trying to deploy it
1- Try to replace a slash forward path
<link rel="stylesheet" type="text/css" href=" {% static '/css/reset.css' %}">
2- whitenoise
pip install whitenoise
Then, set it to "MIDDLEWARE" in "settings.py". Finally, CSS is loaded successfully:
MIDDLEWARE = [
# ...
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware", # Here
# "whitenoise" will solve "MIME type" error then CSS is loaded successfully:
]
3- change your static URL like that:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
I think your mistake is that you put in a space in front of your static link
<link rel="stylesheet" type="text/css" href=" {% static 'css/reset.css' %}">
Try removing the space in front of {% so it will become
<link rel="stylesheet" type="text/css" href="{% static 'css/reset.css' %}">
%20 is translated to a space character in URL's, so that why I think that's the issue
I downloaded a template in the form of a zip file on my machine. It has a file for a homepage, auth-login.html. If I load this on its own then it loads correctly, I see styling and I don't get any console errors.
But it seems like I can't get this template to load its css and styling in my Django project via python manage.py runserver with DEBUG=true. I'm trying to just get this on a development server and I haven't really been able to get past step 1. When I try to go to my application's home page, I see unstylized times new roman text in my browser. No styling loads on the page at all. I'm not getting server/console errors either.
My Django project is of the following structure
lpbsproject/
project_root/
staticFiles/ (STATIC_ROOT, where collectstatic copies to)
project_app/
settings.py
urls.py
wsgi.py, asgi.py, __init__.py...
static/ (STATIC_URL, original location of static files)
assets/ (this folder is copied/pasted from the template .zip)
css/, js/, ...
user_auth/
migrations
views.py
admin.py, models.py, apps.py, test.py ...
templates/
manage.py
Here's the <head> of my html file with all the <link> and <script> statements. These currently aren't generating errors.
{% load static %}
<!doctype html>
<html lang="en">
<head>
<title>Login template from online</title>
<link rel="shortcut icon" href="{% static 'assets/images/favicon.ico' %}">
<link href="{% static 'assets/css/bootstrap.min.css' %}" id="bootstrap-style"/>
<link href="{% static 'assets/css/icons.min.css' %}" type="text/css" />
<link href="{% static 'assets/css/app.min.css' %}" id="app-style" type="text/css" />
<script src="{% static 'assets/libs/jquery/jquery.min.js' %}"></script>
<script src="{% static 'assets/libs/bootstrap/js/bootstrap.bundle.min.js' %}"></script>
<script src="{% static 'assets/libs/metismenu/metisMenu.min.js' %}"></script>
<script src="{% static 'assets/libs/simplebar/simplebar.min.js' %}"></script>
<script src="{% static 'assets/libs/node-waves/waves.min.js' %}"></script>
<script src="{% static 'assets/js/app.js' %}"></script>
</head>
In settings.py, this is how BASEDIR and the static file location are specified
BASE_DIR = Path(__file__).resolve().parent.parent # points to project_root/ directory
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticFiles')
There's ~1200 files in project_root/static/assets/ and I am seeing these get copied into project_root/staticFiles from python manage.py collectstatic. Last night I was dealing with some weridness where none of the js files were getting copied via the collectstatic command.
and urls.py for curiosity sake...
from django.contrib import admin
from django.urls import path
from django.contrib import admin
from django.urls import path, include
from user_auth import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.userLogin, name='loginHome'),
path('login', views.userLogin, name='login'),
path('logout', views.userLogout, name='logout'),
path('registration', views.userRegistration, name='registration'),
path('dashboard', views.dashboard, name='dashboard'),
]
So if python manage.py collectstatic is working... why am I still not able to see any styling at all? I'm not really sure what's going wrong here. It's felt way too difficult to just get a simple /static/ folder working for this project.
The terminal using python manage.py runserver isn't even showing requests for most of these css or js files. I just see
[24/Nov/2020 12:48:00] "GET / HTTP/1.1" 200 7194
[24/Nov/2020 13:25:39] "GET /static/assets/libs/bootstrap/js/bootstrap.bundle.mi
n.js.map HTTP/1.1" 404 1883
[24/Nov/2020 13:25:39] "GET /static/assets/libs/metismenu/metisMenu.min.js.map HTTP/1.1" 404 1853
[24/Nov/2020 13:25:39] "GET /static/assets/libs/node-waves/waves.min.js.map HTTP /1.1" 404 1844
I was able to get an answer when I posted about this on django forums.
No one here caught the html errors. I was inconsistently using type=text/css and rel='stylesheet'. Also <link> tags can end with >, not />.
I tried fetching static files for my website but nothing seems to work even the other stackoverflow answers.
please help on this.
settings.py -
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static','static_root')
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static','static_dirs')
]
File is present in :
parent_folder>static>static_dirs>css>cover.css
HTML
<html lang="en">
{% load staticfiles %}
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="Aman Turate">
<title>Aman Turate - Resume</title>
<link rel="stylesheet" href="{% static 'css/cover.css' %}">
This works for me. Update your settings.py to this
.........
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
.........
Make sure the static folder is in the root (i.e where manage.py is)
There are several things to consider here and I am not sure which applies because I'm working on pure assumptions of your situation without knowing:
What is BASE_DIR set to
Have you run manage.py collectstatic
what is your server setup or are you just working off the django development server?
Where are the files you're trying to link to actually placed
Anyway here is some info I hope will be useful. I will break down how the settings files relates to your template file and hopefully that will help you debug your problem.
STATIC_URL = '/static/' -- > the value of this is what will be appended to the static file you are linking in your template. It is the relative url after your domain name. So {% static 'css/styles.css' %} will be rendered as /static/css/styles.css in your html page when it is loaded.
STATIC_ROOT is the absolute path of where your files are located on disk. It tells django where to place all static files collected from your apps when you run manage.py collectstatic see here for details.
STATICFILES_DIRS tells django where to find project static files. By default Django will look for a static directory in each registered app and collect the files in there and place then in your STATIC_ROOT folder. If you want to put static files in a different directory in your project and you want django to know about it then you list those paths in this config variable.
With your code:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static','static_root')
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static','static_dirs')
]
{% static 'css/cover.css' %} is translating to /static/css/cover.css, your telling django the root directory to collect static files is <your BASE_DIR>/static/static_root so here you can see that there might be a miss match in locations. Again I don't know if you ran collectstatic. your STATICFILES_DIR is just going to look for static files in <your BASE_DIR>/static/static_root to then put them in <your BASE_DIR>/static/static_root ... if that makes sense.
I'm developing django website and am using bootstrap, I can see the styles on chrome browser but not firefox.
firefox inspection shows 404 error for the bootstrap and chrome doesn't. Thankful for any idea.
Code :-
#settings.py
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_URL = '/static/'
STATIC_ROOT = '%s/coffestatic/' % (BASE_DIR)
STATICFILES_DIRS = ['%s/website-static-default/'% (BASE_DIR),
("bootstrap", '%s/bootstrap' % (BASE_DIR)),]
HTTP file.html
<head>
{% load static %}
<link href="{% static'bootstrap/css/bootstrap.css'%}"rel="stylesheet">
</head>
Files structure
BASEDIR
|--ProjectFolder
|------Apps
|--BootstrapDir
|------css
Work flow
Define static files
python manage.py collectstatic
Define styles in html
run project
Thanks
I'm not sure if your settings.py files are correct as they are different from how I would set things up. That being said, I'm no expert and you may well be running a different version of django to me. What I did notice though is you don't have a file type on your link file. Maybe Chrome is fine without this but maybe Firefox is having a hissy fit without it. Try changing:
<link href="{% static'bootstrap/css/bootstrap.css'%}"rel="stylesheet">
to
<link href="{% static'bootstrap/css/bootstrap.css'%}"rel="stylesheet" type="text/css">
Just a guess....
Using bootstrap starter file in your html file will help; as I have done the same and it helped.
Add these files at the end in body section:
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRS
and add these files at the starting in head section:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
I'm a beginner at django so not sure about it but it worked for me.
In project folder create a directory with any name. Let's name __shared__ and put the css and jss folders inside the directory
and in settings.py
at bottom put this code
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "__shared__"),
]
My settings.py contains the following configuration parameters.
STATIC_ROOT = ''
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
'C:/Users/ABC/Desktop/DBMS/DjangoProject/tvshows',
)
My project's CSS file is located at C:/Users/ABC/Desktop/DBMS/DjangoProject/tvshows/static/default.css.
I have a mock HTML file that should pull in the CSS content, but the URL is a 404.
<link rel="stylesheet" href="{{ STATIC_URL }}static/default.css" />
What am I doing wrong?
Things to check:
DEBUG = True in settings.py
urls
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf goes here ...
urlpatterns += staticfiles_urlpatterns()
use context processor or load static if {{ STATIC_URL }} isn't working
If {{ STATIC_URL }} isn't working in
your template, you're probably not
using RequestContext when rendering
the template.
As a brief refresher, context
processors add variables into the
contexts of every template. However,
context processors require that you
use RequestContext when rendering
templates. This happens automatically
if you're using a generic view, but in
views written by hand you'll need to
explicitally use RequestContext To see
how that works, and to read more
details, check out Subclassing
Context: RequestContext.
<link rel="stylesheet" href="{{ STATIC_URL }}default.css" />
You need to also edit your urls: