pythonhtmlflaskbootstrap-4

Import Bootstrap with Flask- HTTP 404


I've tried to import bootstrap an archive but I've received an HTTP 404 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

<!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>
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)

Solution

  • 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:

    1. (most common usage)
    `<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style/bootstrap.css') }}">`
    
    1. 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')