Link to style.css not working - python

I am pretty new to web programming and Flask. I'm trying to link a .css file to the head of my base.html file. I can render the content of the website but not the styles from the .css file. This is my directory:
app
templates
base.html
index.html
views.py
static
style.css
In the head of base.html i wrote:
<head>
...
<link rel="stylesheet" type="text/css" href="/static/style.css">
</head>
I also tried this one:
<head>
...
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
</head>
And also some variations copying the .css file around my directory. Still no formatting on the website.
Some further information: By running the views.py I render the index.html which extends the base.html - I don't know if this might be relevant.

Please try this . It may help
in .py file
from flask import Flask, request, send_from_directory
# set the project root directory as the static folder, you can set others.
app = Flask(__name__, static_url_path='')
#app.route('/static/<path:path>')
def send_css(path):
return send_from_directory('static', path)
in .html file
**
<head>
...
<link rel="stylesheet" type="text/css" href="../../../static/style.css">
</head>
**
edit :
<head>
...
<link rel="stylesheet" type="text/css" href="../../../static/style.css">
</head>

I got it! My directory division was wrong. I put the static folder outside of the app folder - I do not know why but Python could not link outside of the app folder. Thank you for your help, everyone!

please try this and please give path to static_folder correct means it must point to the 'static' directory.
import os
from flask import Flask, request, send_from_directory
app = Flask(__name__, static_folder = 'path/to/folder/of/staticfiles')
#in your case it is 'static' directory.
#app.route('/static/<path:path>/<filename>')
#app.route('/static/<filename>')
def send_css(**kwargs):
filename = kwargs.get('filename')
path = kwargs.get('path')
if path:
return send_from_directory(os.path.join(static_folder,path), filename)
else:
return send_from_directory(static_folder, filename)
This will also read .css files from any subdirectory of your 'static' directory.
just keep this in your index.html.
<head>
...
<link rel="stylesheet" type="text/css" href="/static/style.css">
</head>
I hope your are Extending base.html in index.html
and rendering index.html from flask.
And Did you understand what path you have to give in your static_folder in app = Flask(__name__, static_folder = 'path/to/folder/of/staticfiles') ????
You have to add path of your directory where .css file is kept means your's path of 'static' folder.

Related

Import Bootstrap with Flask

I've tried to import bootstrap an archive but i've face this error:
"GET /bootstrap.css HTTP/1.1" 404
While when I use this tag link it works perfectly.
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
It is possible to import bootstrap as a file while using Flask? If don't, I would like to know why, please
html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="bootstrap.css">
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<h1>Hello User</h1>
{% block content %}
{% endblock %}
</body>
</html>
python:
from flask import Flask, url_for, redirect, render_template
app = Flask(__name__)
#app.route("/")
def home():
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True)
You can try to link the bootstrap using the link tag that they give you in the docs instead of having a file.
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
First thing first, by answering your question: It is possible to import bootstrap as a file while using Flask? If don't, I would like to know why:
Yes it is, you just did it but you only have to link insert this css file in the right place and point it with the right command. Once is downloaded is just like any other CSS file.
For my understanding you have imported the bootstrap by downloading the 'Compiled CSS and JS' from this here ===> https://getbootstrap.com/docs/4.5/getting-started/download/
Assuming that your Boostrap file in within a 'Static' folder and then inside a 'style' as so:
/app
- app.py
/views
- view.py
/templates
- index.html
/static
/style
- bootstrap.css
This both will work for you:
(most common usage)
`<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style/bootstrap.css') }}">`
Example number one depends where in the directory the .html is at, in this example it would be just below templates and is 'index.html
<link rel="stylesheet" type="text/css" href="../static/style/bootstrap.css">
The most important thing is that the css file is in the static folder and it must be correctly pointed at.
Some more reference of really good answer about this topic:
Application not picking up .css file (flask/python):
Note that you can override the static folder path:
app = Flask(__name__, static_url_path="/STATIC_FOLDER", static_folder='STATIC_FOLDER')
More regarding change static folder default
From Flask DOCS
Put bootstrap.css in your static directory, then:
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='bootstrap.css') }}">

Django only serving a single static file

I just got started in Django a few days ago from Ruby and have only run into one really annoying problem that I just can't seem to figure out on my own. I've tried everything I can think of to no avail.
I am trying to serve up two static files, a custom CSS file (style.css) and a bootstrap.min.css file.
While this should be very easy as everybody keeps telling me, I must be staring at the outside of the box because I can't fix it. I would like to note, it does not work in both live (which I don't expect it too because I don't have a root set) or local environments. It currently will only serve up bootstrap.min.css
EDIT:
When collectstatic is run, it passes through. I have set STATIC_ROOT to 'STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
my settings file:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
My Main Template:
<head>
<meta charset="utf-8">
<title>{% block title %}Django Boards{% endblock %}</title>
<link href="https://fonts.googleapis.com/css?family=Peralta" rel="stylesheet">
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
My File Structure:
Main Project
boards
project1
static
css
bootstrap.min.css (loads first files)
style.css (wont load second file)
templates
manage.py
db.sqlite3

Static files not working, using jinja in Flask

I'm a beginner using Flask. My static files don't working, the root
I've this tree directories :
/ <-------------- launching (flask run) the site, here.
/static
/static/css
/static/js
/static/img
/flask_mysite
/flask_mysite/log
/flask_mysite/templates
The flask app variable :
$ echo $FLASK_APP
flask_mysite/__init__.py
To navigate in the root / folder, using an vagrant VM :
flask run --host=192.168.56.101
In the /flask_mysite/__init.py__ I've the jinjia config :
flask_mysite.jinja_env.globals['static'] = (
lambda filename: url_for('static', filename=filename)
)
from flask_mysiteimport views, models
if __name__ == '__main__':
flask_mysite.run(debug=True)
And, in the /flask_mysite/templates/base.html, for example :
<link rel="stylesheet" href="{{ static('css/main.css') }}">
And so, the html generated :
<link rel="stylesheet" href="/static/css/main.css">
Can anobody can help me please ? :)
Thanks.
Fabrice
You're using wrong the static files: http://exploreflask.com/en/latest/static.html
<link rel="shortcut icon"
href="{{ url_for('static', filename='img/favicon.ico') }}">
This is the code that Flask documentation uses for static files, the way are you using it seems to be the Django way
EDIT:
Your flaskapp.py
app = Flask(__name__)
#app.route("/")
def home():
return render('template.html')
Your template.html
<!doctype html>
<html>
<head>
<link href="{{ urlfor('static' , filename='css/yourcss.css'}}">
<script src="{{ urlfor('static' , filename='js/yourjs.js'}}"></script>
</head>
<body>
<!-- the rest of your html -->
</body>
</html>
Assuming that you have "static/css/yourcss.css" and "static/js/yourjs.js" and the .py file is in the root of the folder with the static folder

Tornado - why does static files without StaticFileHandler donot work?

I am new to Tornado. I am trying to link a CSS file to the html template. I am using jinja2 with Tornado. But due to some unknown reasons the CSS file is not loading up.
EDIT: I have created my custom render_template function which is working fine.
Directory structure:
app.py
static
css
custom.css
templates
index.html
Here is my Request Handler's Class:
class Index(RequestHandler):
def get(self):
path = os.path.join('static/css/', 'custom.css')
return self.write(render_template('index.html', path = path))
and here is my index.html template:
<!Doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="{{path}}"/>
</head>
<body>
<div>
<div class="header">
asdasdasd
</div>
</div><!--wrapper-->
</body>
</html>
but the browser is returning the 404-NotFound error for the css file with the correct url, that is http://localhost/static/css/custom.css
Here is a guide on how to link static files in tornado:
http://tornado.readthedocs.org/en/latest/guide/running.html#static-files-and-aggressive-file-caching
Important is the 'static_path' setting in your settings dictionary:
settings = {
"static_path": os.path.join(os.path.dirname(__file__), "static")
}
Now you should be able to use it.

Stylesheet not working in django

I have tried linking a stylesheet to my template in django and it doesnt do anything:
the template(called base.html)
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}base.css">
</head>
<body>
<h1>Welcome to {{ page }}</h1>
</body>
</html>
This is the settings about the static files:
STATIC_URL = '/static/'
STATICFILES_DIRS = ('C:/Users/GAL/PycharmProjects/sqvatPreAlpha/static/',)
The way my project is built:
http://i.imgur.com/o44QSEk.png
What should I do to make it work?
You haven't mentioned if this is a dev or production box. If the latter, make sure you run:
python manage.py collectstatic
This will collect all your static files that you have in the Django project root, and copy them to the STATIC_URL directory. If you are still running into problems after trying this, you most likely have something incorrectly defined in your settings file.
You have to add {% load staticfiles %} at the beginning of base.html
Also, it seems you need to add .cssto your css file.

Categories

Resources