Flask app can't load CSS file from static folder - python

So my file directory looks like this:
/templates
--base.html
/static
--/css
----base.css
In the of my base.html file I have this line:
<link rel="stylesheet" href="{{ url_for('static', filename='css/base.css') }}">
However, when I run the app the base.css file isn't applied to the base.html page. In my browser I get the following error in the console:
GET http://0.0.0.0:8081/static/css/base.css net::ERR_ABORTED 404 (NOT FOUND)
I've already tried clearing my browser cache, hard refreshing the page, and restarting the app, but it still doesn't work.

I've figured out the solution. I just needed to add the following to my __init__.py file:
package_dir = os.path.dirname(
os.path.abspath(__file__)
)
static = os.path.join(
package_dir, "static"
)
app.static_folder=static

Related

CSS not loading completely when i run my python application

I intend to apply basic CSS over my HTML under my python/ flask application. I got a HTML with CSS file from getbootstrap.com.
Link: https://getbootstrap.com/docs/5.2/examples/cover/
The HTML loads up completely when I run it locally (outside the project) but it does not load properly when I try running the application using flask on dev (localhost).
Can someone please suggest a fix here. I have tried placing the CSS file in static folder and then loading it with below approach (adding link to CSS file in my HTML):
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='stylesheets/cover.css') }}">
My project directory looks like:
env
static > stylesheets > cover.css
templates > index.html
app.py
app.py file:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def base():
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True, port=5000)
By default it comes with the following link:
<link href="cover.css" rel="stylesheet">
After running the project, it looks like as attached under the snap. This means that the CSS is getting applied but not completely.

Flask Server in Python ruining looks

I'm trying to render my website inside of flask as I made a backend inside of it.
I've used both of the following codes:
def TestDir():
return render_template('Index/index.html')
and
def HomeDir():
return(open('Templates/Index/index.html').read())
but it shows all glitchy: https://i.1nch.dev/cdn/0pPwq1kDY2Oc9CMM.gif
But on my pc it shows normal: https://i.1nch.dev/cdn/l3LnfmUzyad78Nl5.gif
You need to have a static folder setup for your css and js files unless you override it when you initialize Flask.
Your app directory should look something like this:
/app
- app_runner.py
/templates
/Index
- Index.html
/static
/css
- style.css
To access the css file in your html use something like this:
<link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='css/style.css') }}">

Flask 404'ing on static content I have in an assets directory

My project structure looks like this:
/project home
app.py
/templates/index.html
/templates/assets
and my index.html file has several references to relative stylesheets that look like this:
<link rel="stylesheet" href="assets/css/slick.css">
<link rel="stylesheet" href="assets/css/slick-theme.css">
Same for various JS files that exist in assets/js. Now when I load the page, I get this error:
Loading failed for the <script> with source “http://localhost:5000/assets/js/popper.min.js”. localhost:5000:564:1
There are many of these messages and in the python debugger I see:
127.0.0.1 - - [24/Dec/2019 18:29:16] "GET /assets/js/main.js HTTP/1.1" 404
I tried googling and changing this line in Flask
STATIC_URL_PATH = '/templates/assets/' # Where the css is stored
STATIC_FOLDER = '/templates/assets/'
app = flask.Flask(__name__, static_folder=STATIC_FOLDER,
static_url_path=STATIC_URL_PATH)
But still when I click the index.html page in templates its able to load fine with all the CSS and JS and images, but from Flask, its like the CSS is stripped out.
First, make sure that the templates folder is in the same directory as your app.py:
.
├── app.py
└── templates
└── assets
Then create the Flask instance like this:
STATIC_FOLDER = 'templates/assets'
app = Flask(__name__,
static_folder=STATIC_FOLDER)
1st, /templates and templates (without /) are 2 different paths. The 1st one refers to a templates folder under the root path / of your system, which certainly isn't the one you want. The 2nd one refers to a templates folder in the same directory, which is the one you want.
2nd, there is no need to specify static_url_path if it's just the same as the static_folder, because that's the default behavior ("Defaults to the name of the static_folder folder").
Then, in your HTML files, instead of hardcoding the paths to the assets folder, let Flask build the URL for you. See the Static Files section of the Flask docs:
To generate URLs for static files, use the special 'static' endpoint
name:
url_for('static', filename='style.css')
By default, it will look for static files under the static folder (ex. static/style.css) because that it is the default value for the static_folder parameter in the Flask constructor. When you set it to templates/assets, Flask will use that and will automatically build the correct URL with url_for.
<link rel="stylesheet" href="{{ url_for('static', filename='css/slick.css') }}">
Note:
Make sure that, when testing the loading of static files, clear your browser's cache first or test your app on private/incognito mode of your browser, to force re-downloading of static files.

Django static files do not resolve constant 404 errors

I am new to Django current version I'm running is 1.11 with python 3. I have configured the static file stuff as the docs suggest. Inside installed apps I have 'django.contrib.staticfiles'
nonprofit/nonprofit/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__)))
STATIC_URL = '/static/'
STATICFILES_DIR = (
os.path.join(BASE_DIR, "static/"),
)
And django seems to be working as far as putting the right path in the template. Though even if I hardcode the path into the template the browser still gives a 404 not found.
I have a base.html template, with some css.
{% load staticfiles %}
<!--Bootstrap-->
<link rel="stylesheet" href="{% static 'css/bootstrap.css' %}">
<link rel="stylesheet" href="/static/css/bootstrap-theme.css">
My directory structure is --
nonprofit
- goals
- nonprofit
- static
- css
bootstrap.css
bootstrap-theme.css
- templates
base.html
db.sqlite3
manage.py
From the browser it shows both 404 not found errors as well as not being able to go straight to the files-
GET http://127.0.0.1:8000/static/css/bootstrap.css 127.0.0.1/:19
GET http://127.0.0.1:8000/static/css/bootstrap-theme.css 127.0.0.1/:20
I don't think the problem is with django because it shows the right path, but even the hardcoded one cannot be accessed through the browser. I'm running the development server. Whats going on with this stuff? Do I have something wrongly configured or lacking configuration? Any help is appreciated. I have looked at all the suggested posts and have tried various things without any good results.
The setting name is STATICFILES_DIRS. You are missing the S.

Django CSS. I get the HTML page with no CSS

I have had this problem for a while now, I have been trying to move my CSS file all over the place and changing the settings, and even messing with the media url stuff, which I don't believe I should be now that I have read other questions.
My CSS file is in the /home/justin/test/static/ directory. My templates are in the /test/templates directory.
My settings are:
STATIC_ROOT = '/home/justin/test/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
'/home/justin/test/static/',
)
My urls are:
urlpatterns = patterns('',
url(r'^$', 'views.home'),
# Static Files
url(r'^static/(?P<path>.*)$','django.views.static.serve', {'document_root':settings.MEDIA_ROOT}),
)
I have all three in my main template.
<link rel="stylesheet" href="/static/style.css" />
<link rel="stylesheet" href="{{ STATIC_URL }}style.css" />
<link rel="stylesheet" href="{{ STATIC_URL }}/style.css" />
They come out:
<link href="/static/style.css" rel="stylesheet"></link>
<link href="style.css" rel="stylesheet"></link>
<link href="/style.css" rel="stylesheet"></link>
The first comes out to the correct file, but it doesn't work.
Any help is really appreciated. Thank you.
My views.py:
from django.shortcuts import render_to_response
def home(request):
return render_to_response('index.html',{})
My error from the terminal is:
[16/Aug/2013 21:00:21] "GET /static/style.css HTTP/1.1" 500 1729
You need to pass request in RequestContext of your views
def home(request):
return render_to_response('index.html', locals(), context_instance = RequestContext(request))
Only then your session data will be passed to the template and {{ STATIC_URL }} will work.
Here are some tips to help you solve this problem.
First, anything to do with MEDIA_ is referring to files that are uploaded to the system by users; and STATIC_ refers to files that are part of your application.
STATIC_ROOT should point to the file system path where the collectstatic command will dump all the static files from all your applications. When you are deploying the application into a production environment, you run collectstatic (which will overwrite everything in the directory pointed to by STATIC_ROOT) and then copy the contents of this directory to a location that is mapped to the url that STATIC_URL points to.
In summary:
If your application needs any static files (images, javascript, css, etc.) create a directory called static in your application's directory (the same location where you have models.py) and add the files there.
STATIC_ROOT should point to a directory where all the images, css, javascript, etc. will be dumped by the collectstatic command. This is only used when you want to move your application to a production server. The collectstatic command will grab all the files in all the static directories in your applications that are listed in INSTALLED_APPS (including the ones from the django.contrib like the admin interface) and dump them in this directory. You would then take this directory and copy or move it to your web server.
STATICFILES_DIRS is a directory where any static files that are not part of any specific application should be stored. If this location is set, then django will also look here for static files.
STATIC_URL = the URL path that is configured in your web server to point to the location where all the files in STATIC_ROOT are located.
The {% static %} tag will always point to the STATIC_URL variable. In order to use this tag you must have {% load staticfiles %} at the top of any template that is using the tag; even if the template is inheriting from one that already as the load line in it.
You don't need anything fancy in your urls.py unless you are using django to serve your static files (which you should not do). Use the web server to handle static files. If you are running with DEBUG = True and using runserver, then django will take care of handling static files for you automatically as a courtesy during development.
For any user uploaded files which are controlled by the various MEDIA_* settings you need to handle these manually during development; and for this you can use the following snippet in your urs.py. Again, keep in mind this is only for development - do not use this in production:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# ... the rest of your URLconf goes here ...
)
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
Please read the static files section in the manual; from where I have summarized the above points.
Finally, you should use the render shortcut when using methods in your views. This makes sure that the proper request context is always sent.
you must use this tag ({% load static from staticfiles %}) in your template :
{% load static from staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'style.css' %}" />
In your urls, you should serve from the STATIC_ROOT not the MEDIA_ROOT setting
url(r'^static/(?P<path>.*)$','django.views.static.serve', {'document_root':settings.STATIC_ROOT})
Also, you need to pass RequestContext on your views, like stated in other answers.
In development mode (which means DEBUG=True in settings.py), to serve static files
Simply put the following lines in urls.py
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf here ...
urlpatterns += staticfiles_urlpatterns()
In production mode, you should use nginx/apache in front of django to serve static files.
Refs: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/
There's a line in your question:
url(r'^static/(?P<path>.*)$','django.views.static.serve', {'document_root':settings.MEDIA_ROOT}),
Normally, settings.MEDIA_ROOT is for user uploaded files, which is a different folder from settings.STATIC_ROOT.

Categories