Why is the Flask element in my HTML not working? - python

I am transferring data from a python sheet to an HTML page using Flask. However, the corresponding code in the HTML file is not even changing color as it is supposed to, I don't think it's registering it as valid code. It is just treating the code as a string and outputting the code on the screen.
Here is the Python code in app.py:
from flask import Flask, render_template
name = ("Rachel", "Lola")
#app.route('/', methods = ['GET', 'POST'])
def data():
return render_template(Visualization.html, name=name)
Here is the HTML code that's in a file called Visualization.html:
{% for element in name %}
<p>{{element}}</p>
{% endfor %}
Any ideas on how to make this transfer the data properly? Thank you so much.

Your html file should look like this,if you are new to web dev, you should know that every html file should look like this:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Your title</title>
</head>
<body>
{% for element in name %}
<p>{{element}}</p>
{% endfor %}
</body>
</html>

you have an error in the python file... you should type it as follow
return render_template('Visualization.html', name=name)

Related

CSS doesn't work on pages that have variables in their url

I create a page where css works on every page except the page that is saved in the main.py file like this
#app.route('/sendKontakt/<nm>/<em>/<tx>', methods=['GET', 'POST'])
def sendKontakt(nm, em, tx):
return render_template('kontaktSucces.html', imie=nm, emile=em, wiadomosc=tx.replace("_", " "))
CSS doesn't work because url has <>.
The html code of this page looks like this:
{% extends 'base.html' %}
{% block title %}| Kontakt{% endblock %}
{% block content %}
<h1>Dziękujemy za kontakt!</h1>
<p>ImiÄ™: {{imie}}</p>
<p>Emile: {{emile}}</p>
<p>Wiadomosc: {{wiadomosc}}</p>
{% endblock %}
In base.html file header looks like
<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="static\css\style.css" type="text/css">
<link rel = "icon" href = "static/img/smallicon.png" type = "image/x-icon">
<title>{% block title %}{% endblock %}</title>
</head>
I apologize for not English words but they shouldn't get in the way of solving this problem.
Anyone know how to get css styles to work? I will probably not be able to write back for a few hours. Regards Kuba

How to add number in front of list item with Jinja Flask?

I am learning flask & have created a very basic page which renders Jokes from the pyjokes library
Here my doubt is though the jokes are populating in the list but all the items are having 1. in front of them how can I increase these number
Python code
from flask import Flask, redirect, url_for, render_template
import pyjokes
import sys
app = Flask(__name__)
jokes = pyjokes.get_jokes()
# Defining the home page of our site
#app.route("/") # this sets the route to this page
def home():
# print(jokes)
return render_template("1.html" , jokes = jokes) # some basic inline html
#app.route("/<anything>")
def user(anything):
return f"Hello {anything}! plz go back nothing here "
if __name__ == "__main__":
app.run(use_reloader=True,debug=True)
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">
<title>Document</title>
</head>
<body>
<h1>Welcome to home page</h1>
<h3>Below are jokes frok python modules jokes</h3>
{% for x in jokes %}
<ol><li>{{x}}</li></ol>
{% endfor %}
</body>
</html>
Sample Current Output
Welcome to home page
Below are jokes frok python modules jokes
1.Complaining about the lack of smoking shelters, the nicotine addicted Python programmers said 1.there ought to be 'spaces for tabs'.
1.Ubuntu users are apt to get this joke.
1.Obfuscated Reality Mappers (ORMs) can be useful database tools.
& so on ...
Expected Output
Welcome to home page
Below are jokes frok python modules jokes
1.Complaining about the lack of smoking shelters, the nicotine addicted Python programmers said 1.there ought to be 'spaces for tabs'.
2.Ubuntu users are apt to get this joke.
3.Obfuscated Reality Mappers (ORMs) can be useful database tools.
& so on ...
Try this
<!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">
<title>Document</title>
</head>
<body>
<h1>Welcome to home page</h1>
<h3>Below are jokes frok python modules jokes</h3>
<ol>
{% for x in jokes %}
<li>{{x}}</li>
{% endfor %}
</ol>
</body>
</html>
Looks like you're creating a new ordered list for each element, instead of one ordered list with all the elements contained in it.

Python Flask favicon not showing up [duplicate]

This question already has answers here:
How to serve static files in Flask
(24 answers)
Closed 1 year ago.
I have been trying for the last 45 minutes to figure out how to get my favicon on my flask page.
Here is my current code:
from flask import Flask, render_template, send_from_directory, url_for
import os
app = Flask(__name__)
#app.route("/")
def home():
return render_template("index.html")
#app.route("/store")
def store():
return render_template("store.html")
#app.route("/games")
def games():
return render_template("games.html")
#app.route("/americanstudios")
def americanstudios():
return render_template("as.html")
#app.route("/pear")
def pear():
return render_template("pear.html")
#app.route("/favicon.ico")
def fav():
return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico', minetype='image/vnd.microsof.icon')
if __name__ == "__main__":
app.run(debug=True)
With the base html being this:
<!DOCTYPE html>
<html>
<title>{% block title %}{% endblock %}</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font- awesome.min.css">
<head>
<link rel="shortcut icon" href="{{ url_for('static',filename='favicon.ico') }}">
</head>
<style>
body,h1,h2,h3,h4,h5,h6 {font-family: "Raleway", Arial, Helvetica, sans-serif}
</style>
<body class="w3-light-grey">
<!-- Navigation Bar -->
<div class="w3-bar w3-white w3-large">
</i>newtech
Store
Games
American Studios
PEAR Electronics
Log In
</body>
<div class="w3-main" style="margin-left:250px">
<div class="w3-row w3-padding-64">
<div class="w3-twothird w3-container">
{% block content %}
{% endblock %}
</div>
</div>
</div>
</html>
And this is index.html
{% extends "base.html" %}
{% block title %}newtech inc.{% endblock %}
{% block content %}
<h1 class="w3-text-teal">Home</h1>
<p>Welcome to newtech inc, where we have the coolest new items for all purposes. Whether it's a new movie to watch, or a fun game, or maybe something else, we're here for you.</p>
{% endblock %}
The only line in head in base.html should load my favicon from the static folder as the favicon for the page. But for some reason, the favicon stays as the default favicon for the index page and all other pages.
My favicon is a 64 X 64 .ico file
And it is located in my static folder
And yes the static folder is in the same directory as main.py
But even with all of this the favicon still does not show up.
And yes I am running the correct main.py
Also tried this
Yet no luck. Can anyone help me?
to look for network error, you would need to look at the network tab of the dev tools. it shows that your get for favicon.ico is failing with 404. fix? add static folder to your app (refer 1 in code), and the add get for favicon and return the file - refer 2 in code.
from flask import Flask,render_template,send_from_directory
app = Flask(__name__, static_folder='static') # 1 ( either add here or add through some os join)
import os
#app.route("/")
def home():
return render_template("index.html")
#app.route("/static/favicon.ico") # 2 add get for favicon
def fav():
print(os.path.join(app.root_path, 'static'))
return send_from_directory(app.static_folder, 'favicon.ico') # for sure return the file
if __name__=="__main__":
app.run(debug=True)
the folder structure will be like :
Did you check out the Flask documentation already? They recommend a slightly different reference than what you have there:
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
https://flask.palletsprojects.com/en/1.1.x/patterns/favicon/?highlight=favicon

How can I make a variable number of links using Flask and HTML?

Let me explain my situation. I am making a note app using flask and HTML. I want it to be so that when you click on one of the links, it takes you to a link with the title, but it isn't working! I am using ArangoDB.
Here is my HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{welcome}}</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma#0.9.1/css/bulma.min.css">
</head>
<body>
<section class="section has-text-centered">
<h1 class="title is-2">Hi {{username}}!</h1>
Create a note
Log out
</section>
<section>
<ul>
{% for note in notes %}
<li>
<a class="button is-light is-fullwidth" href="/{{note.title}}">{{note.title}}</a>
</li>
{% endfor %}
</ul>
</section>
</body>
</html>
and here is the relevant python code:
#app.route("/notes")
def notes_page():
global notes
notes = db.collection("Users")[username]["notes"]
if username != "":
return render_template("notes.html", username=username, notes=notes, welcome=welcome)
else:
return redirect(url_for("home"))
try:
for i in notes:
url = "/" + i["title"]
#app.route(url)
def view_note():
return render_template("view.html", title=i["title"], note=i["note"])
except NameError:
pass
I run the code and I clicked a link for a test note I created, and when I was redirected, it showed the 404 error message saying the link wasn't found. Can you please help me fix this? Thanks

Flask render_template() return raw HTML, not processed

I'm workin with flask mail, I want to insert a rendered HTML in my mail.
Here is the code :
Controller :
msg = Message("test", sender='xxx#gmail.com', recipients=[user.get("email")])
msg.body = render_template('/assets/views/emailing/notification.html', name=user.get("name"))
mail.send(msg)
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% if name %}
<h1>Hello {{ name }}!</h1>
{% else %}
<h1>Hello, World!</h1>
{% endif %}
</body>
</html>
So I expect a rendered email, or at least the html as text but with the keys replaced by values.
Here is what i got :
https://i.imgur.com/efDMyDM.png
Any clue of what is happening ?
As you are sending an HTML email, you need to set the html attribute instead of body, like so:
html = render_template('/assets/views/emailing/notification.html', name=user.get("name"))
msg = Message("test", sender='xxx#gmail.com', recipients=[user.get("email")], html=html)
mail.send(msg)

Categories