Why does bootstrap not show up when I run my website? [duplicate] - python

This question already has answers here:
Link to Flask static files with url_for
(2 answers)
Closed 1 year ago.
I am new to web development,and I was building my first website with Flask.When I first runned the website,Bootstrap was not working,after that I went in inspect mode and it gave me some errors.
I tried emptying the cache,but it did not change anything.
The projects folders are arranged like this:
This is the HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/bootstrap.css">
{% if title %}
<title> Project--{{Title}} </title>
{% else %}
<title> Project </title>
{%endif%}
</head>
<body>
<div class="alert alert-primary" role="alert">
Hello
</div>
<script src="js/bootstrap.js"></script>
</body>
</html>
The python code:
from flask import Flask,render_template,url_for
app=Flask(__name__,template_folder='Template')
#app.route("/")
def home():
return render_template('Home.html',title='Home')
if __name__=='__main__':
app.run(debug=True)
How can I fix this issue?
Thanks in advance!

You have to keep js and css folder in a folder named static at same level that of templates folder where you will keep only html files.
You can use href="{{ url_for('static', filename='css/bootstrap.css') }}" for a css file named bootstrap.css which is in css folder in static folder. Same you have to do with us files , src="{{ url_for('static', filename='js/bootstrap.js') }}"

Related

styles.css file is not working. how to solve the problem?

I made a website and got to the point where you need to connect styles.css, but after all the manipulations, my site has not changed and no design has been connected. I tried to rewrite css and html, tried different tips, but nothing helped me. any ideas?
I would be grateful for any advice!
1part base.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>{{title}}</title>
<link type="text/css" href="{% static 'women/css/styles.css' %}" rel="stylesheet" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="shortcut icon" href="{% static 'women/images/main.ico' %}" type="image/x-icon"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<table class="table-page" border=0 cellpadding="0" cellspacing="0">
<tr><td valign=top>
{% block mainmenu %}
<div class="header">
<ul id="mainmenu" class="mainmenu">
<li class="logo"><div class="logo"></div></li>
{% for m in menu %}
{% if not forloop.last %}
<li>{{m.title}}</li>
{% else %}
<li class="last">{{m.title}}</li>
{% endif %}
{% endfor %}
</ul>
<div class="clear"></div>
</div>
{% endblock mainmenu %}```
I've added screenshots below if anyone needs them.
[1][1]
[2][2]
[3][3]
[4][4]
- PS I have already tried these options, gives an error
```<link type="text/css" href="{% static 'women/css/styles.css' %}" rel="stylesheet" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="shortcut icon" href="{% static 'women/images/main.ico' %}" type="image/x-icon"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">```
[1]: https://i.stack.imgur.com/3exw2.png
[2]: https://i.stack.imgur.com/ye5k7.png
[3]: https://i.stack.imgur.com/ZKSs6.png
[4]: https://i.stack.imgur.com/eQRvd.png
Don't know if its the same issue but I find clearing the cache can fix styling issues (ctrl+f5)
Check static dirs in settings.py and correct static dirs, because it may cause issues in connecting with dirs.
[for reference I am giving you settings of static dirs below]
settings.py
STATIC_URL = "/static/"
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media")
If the settings are okay then remember whenever you change something in CSS browser doesn't Change CSS directly you need to make a hard reset your browser's tab by pressing
Ctrl + shift + R
If it's on server, make sure to collectstatic after you make changes in files of your static folder. To make your static folder updated.
python manage.py collectstatic
Then restart gunicorn and nginx
sudo systemctl daemon-reload
sudo systemctl restart gunicorn
sudo systemctl restart nginx
However if it's in your local computer, you might just need to hard-reload your browser (ctrl+shift+R).
If it still doesn't work, make sure the path of your css file is correct.

Pyscript button

I'm confused. I'm trying to run pyscript button example from - https://jeff.glass/post/7-guis-pyscript/ (first example - counter)
This is the HTML code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hello, World!</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<p id="counter-target">Some Placeholder Text</p>
<py-button>
def on_click(event):
add_one()
</py-button>
<py-script src="myscript.py"></py-script>
</body>
</html>
This is the PYTHON CODE:
internalCount = 0
target = "counter-target"
PyScript.write(target, str(internalCount), append=False)
def add_one():
global internalCount
internalCount += 1
PyScript.write(target, str(internalCount), append=False)
It's showing me the button (using VSC Live server), but nothing happens once clicking on it... also Visual studio code is showing me this error. I don't understand. I shouldn't import anything, right? Thanks
Define two scripts: myscript.py
def add_one(event):
pyscript.write("output", str(global_vars['internalCounter']), False)
global_vars['internalCounter'] += 1
and globals.py
global_vars = {"internalCounter": 1}
declare both of them inside your html file in py-env section:
<py-env>
paths
./globals.py
./myscript.py
</py-env>
be sure to have identation of 4 spaces (no tab chars).
In html declare two pyscript nodes with src attributes pointing to your scripts:
<py-script src='globals.py'></py-script>
<py-script src='myscript.py'></py-script>
change button node as in html below (use pys-onclick) as well as make a div for output.
Complete index.html looks like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hello, World!</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
<py-env>
paths
./globals.py
./myscript.py
</py-env>
</head>
<body>
<py-script src='globals.py'></py-script>
<py-script src='myscript.py'></py-script>
<div id="main">
<p id="counter-target">Some Placeholder Text</p>
<py-button pys-onclick="add_one">
</py-button>
<div id="output">Outputs here</div>
</div>
</body>
</html>
This way you have defined a dictionary (globals.py) where you can manipulate global variables (can define them as you like) within a session. In your myscript.py you can have functions and functionalities that you need for your app. You can in the same manner add more scripts if needed. For it to be working you should declare scripts as paths within py-env section of html and add pyscript node for each of them with src attribute pointing to .py scripts.
As you have py-button defined then your on click event is pys-onclick. I added a div for output too as you can see but it can be done differently too. There should be an id for pyscript.write() function to be operational. Regards...

flask not reading bootstrap.css during runtime (mac)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="/static/bootstrap.css">
<title>Document</title>
</head>
<body>
<div class="container">
<form method = "post" enctype="multipart/form-data">
<h2>Choose your State</h2>
{{form.state_variable}}
<h2>Choose your District</h2>
{{form.district_variable}}
<br>
<br>
<br>
<input type="submit" name="submit" value="submit"/>
</div>
</body>
</html>
I'm new to creating web apps through flask and html. I created a very simple page that takes input from the html file and displays a table in another html. My python flask and html both are running fine. I wanted to add some bootstrap.css, so tried adding the div class=container to the html page using visual studio code. I previewed it with the 'Live Server' in visual studio code and it works fine. However, when I start the local server to work with flask, at that time bootstrap css is not getting applied. What I see is a barebone html page without styles being applied. All functionalities works fine though.
Any help will be much appreciated. Thanks.
Error Message: "GET /css/bootstrap.css HTTP/1.1" 404 -
Note: I'm not sure why the code is looking for "/css/" folder while I have clearly put my css file in the static folder and referenced it
You need to replace href="/static/bootstrap.css" and replace it with:
href="{{url_for('static', filename='bootstrap.css')}}"
You need to do that, because you write in flask like this. Normally you would do it like you did it. Feel free to tell me any errors
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="{{url_for('static', filename='bootstrap.css')}}">
<title>Document</title>
</head>
the above change to href as suggested by the user 'malware' helped resolve this.
I also commented the below line in my python code as that doesn't seem to be the problem
#app._static_folder = '<path>'

Resource interpreted as Stylesheet but transferred with MIME issue when using Flask #app.before_request

I'm trying to add a maintenance page to my Flask site. I have created a route called /maintenance that renders my maintenance.html template. I then added an #app.before_request to check whether the site is in maintenance mode (a Boolean value).
When I request the /maintenance route directly from the browser, the page displays fine:
However, when the route is called from the #app.before_request, it displays like this:
As can be seen from the console window, I'm getting the following message:
'Resource interpreted as Stylesheet but transferred with MIME type text/html'
Here is the code for the /maintenance route and #app.before_request:
#app.before_request
def check_for_maintenance():
if maintenance == True and request.path != url_for('maintenance'):
return redirect(url_for('maintenance'))
#app.route('/maintenance')
def maintenance():
if request.method =='GET':
return render_template('maintenance.html')
Here's the code for the maintenance page (ish, it inherits lots of parent Jinja templates but the important stuff is here):
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="/static/css/theme.css">
<link href="{{ url_for('static', filename='fonts/peenu/stylesheet.css') }}" rel="stylesheet">
<link href="{{ url_for('static', filename='favicon.ico') }}" rel="icon">
</head>
<body>
<div id="maintenanceBackground">
<div id="maintenanceTextParent">
<img id="spannerIcon" src="/static/media/graphics/spanner.png" alt="Spanner icon">
<h1 id="maintenanceText1">We're doing some work at the moment</h1>
<h2 id="maintenanceText2">We hope to be running again soon. Please try again later.</h2>
<img id="whiteLogo" src="/static/media/graphics/logoWhite.png" alt="Custom Crochet logo">
</div>
</div>
</body>
</html>
This is somewhat related to flask. If you try to access the html directly without flask's webserver, the html page loads with applied css, as expected.
To be more specific, actual solution is
to create a "css" folder in "static" folder.
add css in path of ".css" file (update all occurrence for any .css file with expected relative path)
eg.
change => href="{{ url_for('static', filename='stylesheet.css') }}" to href="{{ url_for('static', filename='css/stylesheet.css') }}" OR
change => href="../static/main.css" to href="../static/css/main.css"
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
In your case
try moving stylesheet.css from "fonts/peenu/stylesheet.css" to "static/css" folder.
change => href="{{ url_for('static', filename='fonts/peenu/stylesheet.css') }}"
to
href="{{ url_for('static', filename='css/stylesheet.css') }}"
I had spent some time on this issue and was able to resolve it with above mentioned solution.

Getting error 404 while trying to run flask app in python

attached is the picture of how my directories are upi am trying to run my app with flask, and I am referencing the proper directories, yet I keep getting an error 404 message. I do not know what I am doing wrong.
Here is my the code to run the app in the app.py section:
#app.route('/')
def math():
#return(y)
return render_template('index2.html', variable = y)
if __name__ == "__main__":
app.run(debug = True)
and here is my html code
<!DOCTYPE html>
<html lang="en">
<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="">
<title>Scrolling Nav - Start Bootstrap Template</title>
<!-- Bootstrap core CSS -->
<link href="/static2/static2/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="/static2/static2/css/scrolling-nav.css" rel="stylesheet">
<!-- Bootstrap core JavaScript -->
<script src="/static2/static2/vendor/jquery/jquery.min.js"></script>
<script src="/static2/static2/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Plugin JavaScript -->
<script src="/static2/static2/vendor/jquery-easing/jquery.easing.min.js"></script>
<!-- Custom JavaScript for this theme -->
<script src="/static2/static2/js/scrolling-nav.js"></script>
</body>
</html>
the scrolling -nav.js is in the correct folder for sure.
Please let me know if there is more information needed for this question.
For references to static files in Flask it's considered best practice to use the url_for function e.g.
<script src="{{url_for('static', filename='js/scrolling-nav.js')}}"></script>
Other than that, if that is your full HTML then it's just a javascript file, do you have the basic HTML stuff in there as well? e.g.
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
Content
</body>
<html>
Is index2.html stored in a templates folder?
I got it. My directories name was static2. The directories name must be "static" for the css and js files to be pulled.

Categories

Resources