CSS isn't linking from my Python/Flask application - python

Can't seem to get my style sheet to link, can someone please tell me why?
I'm trying to set up an sample instance with a database, ran on Flask.
I thought it was my folder location, but I've double checked it is on the right place and can't figure out why, spent hours trying to fix it.
My HTML:
{% extends "layout.html" %}
{% block title %}
CS50_Web_Project1
{% endblock %}
{% block body %}
<h1>Login to CS50_Web_Project1</h1>
<form action="{{ url_for('register') }}" method="POST">
<button>Register</button>
</form>
{% endblock %}
My layout.html:
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
<!-- #olaf: own link to own style sheet-->
<link rel="stylesheet" href="css/style.css" type="text/css" >
<!-- #olaf: copied from https://bootsnipp.com/snippets/GaEOX-->
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
{% block body %}
{% endblock %}
</div>
</body>
</html>
My CSS in css/style.css location:
/* style.css */
.note
{
text-align: center;
height: 80px;
background: -webkit-linear-gradient(left, #0072ff, #8811c5);
color: #fff;
font-weight: bold;
line-height: 80px;
}
.form-content
{
padding: 5%;
border: 1px solid #ced4da;
margin-bottom: 2%;
}
.form-control{
border-radius:1.5rem;
}
.btnSubmit
{
border:none;
border-radius:1.5rem;
padding: 1%;
width: 20%;
cursor: pointer;
background: #0062cc;
color: #fff;
}
My application.py:
import os
from flask import Flask, session, render_template, jsonify, request
from flask_session import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
app = Flask(__name__)
#from the internet...# app.config['DATABASE_URL'] = "path_to_db"
# Check for environment variable
if not "DATABASE_URL":
raise RuntimeError("DATABASE_URL is not set")
# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
# Set up database
engine = create_engine("DATABASE_URL")
db = scoped_session(sessionmaker(bind=engine))
#olaf: create a login page that has a form, containing "login" & "register" button
#app.route("/")
def index():
return render_template("index.html")
#olaf: Login button
#app.route("/register", methods=["POST"])
def register():
"""Register for the site"""
return render_template("registerSuccess.html")

To provide CSS file in your Flask template you need to use a specific method for that in your HTML template {{ url_for(STATIC_DIR_NAME, filename=PATH_TO_FILE_IN_STATIC_DIR)}}.
In your layout.html
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
<!-- #olaf: own link to own style sheet-->
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}" type="text/css" >
<!-- #olaf: copied from https://bootsnipp.com/snippets/GaEOX-->
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
{% block body %}
{% endblock %}
</div>
</body>
</html>
Also, if you follow the official documentation tips on the layout should do it.
But if you have a custom project setup then you might need to provide to your app where a static folder is.
For example in your application.py
import os
from flask import Flask, session, render_template, jsonify, request
from flask_session import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_DIR = os.path.join(THIS_DIR, 'specific_path_to_static', 'static')
app = Flask(__name__, static_url_path=STATIC_DIR)
#from the internet...# app.config['DATABASE_URL'] = "path_to_db"
# Check for environment variable
if not "DATABASE_URL":
raise RuntimeError("DATABASE_URL is not set")
# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
# Set up database
engine = create_engine("DATABASE_URL")
db = scoped_session(sessionmaker(bind=engine))
#olaf: create a login page that has a form, containing "login" & "register" button
#app.route("/")
def index():
return render_template("index.html")
#olaf: Login button
#app.route("/register", methods=["POST"])
def register():
"""Register for the site"""
return render_template("registerSuccess.html")
Then the flask template should find the style.css file provided in layout.html file.

The first solution i can propose is that you download the bootstrap files and have them on your local working directory, then make a folder to contain static files and try the following code
<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">

Related

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 you use flask to make the text of your website blue?

How can you use flask to make the text of your website blue? I only know how to display text on your website. My code :
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return '''Hello world'''
Despite the negative feedback from other user, this is not that bad of a question, besides apart of #go2nirvana no one answered your question.
Note
Despite this is more a Front-end question related to CSS or Javascript and not HTML (yes you can embed CSS inline within HTML but is not recommended) what you asked can be achieved in Flask in many ways.
Example 1 -Hard coding, not recommended buy you can do it-
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
my_html = '''
<body style="background-color: #e1eb34;">
<h1 style="color: #002aff;">Hello World</h1>
</body>
'''
return my_html
if __name__ == '__main__':
app.run(debug=True)
or
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return '''
<body style="background-color: #e1eb34;">
<h1 style="color: #002aff;">Hello World</h1>
</body>
'''
if __name__ == '__main__':
Example 2 -Using Jinja2 DOCS##
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def hello_world():
color = {
'blue': '002aff',
'yellow': 'e1eb34',
'green': '28fc03',
'red': 'fc1703',
'purple': 'b503fc'}
return render_template('index.html', color=color)
if __name__ == '__main__':
app.run(debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body style="background-color: #{{color['yellow']}};">
{% for hue in color.values() if hue != 'e1eb34'%}
<h1 style="color: #{{hue}};">Hello World</h1>
{% endfor %}
<h1></h1>
</body>
</html>
Example 3 -Adding request, session, redirect, url_for and more fun
from flask import Flask, render_template, redirect, url_for, request, session
import random
app = Flask(__name__)
app.config['SECRET_KEY'] = 'dev'
color = {
'blue': '002aff',
'yellow': 'e1eb34',
'green': '28fc03',
'red': 'fc1703',
'purple': 'b503fc',
'orange': 'FF9733 ',
'black' : 'FFFFFF',
'light-blue': '0AE5E3',
'pink': 'FF95AE',
'blue-green' : '95FFCA'}
#app.route('/', methods=['GET', 'POST'])
def index():
error = None
if 'color' not in session:
session['color'] = None
session['background'] = None
if request.method == 'POST':
choice = request.form['color'].lower()
if choice not in color:
error = 'Color not in list'
return render_template('index.html', color=session['color'], background=session['background'], error=error )
else:
session['color'] = color.get(choice)
session['background'] = random.choice(list(color.values()))
return redirect(url_for('index'))
return render_template('index.html', color=session['color'], background=session['background'], error=error )
if __name__ == '__main__':
app.run(debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
{% if color%}
<style>
body {
color: #{{color}};
background-color: #{{background}};
}
</style>
{% endif %}
</head>
<body>
<h1>Hello World</h1>
{% if error%}
{{error}}
{% endif %}
<form action="{{url_for('index')}}" method="POST">
<label for="color">Choose a color</label>
<input type="text" name="color">
<input type="submit" value="PRESSS" name="i_talk-with_flask">
</form>
</body>
</html>
Variation with a Macro DOC
{% macro color_mix(color)%}
{% if color%}
<style>
body {color: #{{color}};}
body {background-color: #{{background_}};}
</style>
{% endif %}
{% endmacro%}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
{{color_mix(color)}}
</head>
<body>
<h1>Hello World</h1>
{% if error%}
{{error}}
{% endif %}
<form action="{{url_for('index')}}" method="POST">
<label for="color">Choose a color</label>
<input type="text" name="color">
<input type="submit" value="PRESSS" name="i_talk-with_flask">
</form>
</body>
</html>
Honestly this is only the tip of the iceberg of the option you can have. Now is this reccomended ? Probably not, because this it should be handle with CSS or then handle it with JavaScript.
However there may be planty of instances where you may want to use it from a Flask App, one of there are:
Testing Purposes.
Debugging.
Something related to a Database.
Fun
That's a CSS question, not Flask.
return '<span style="color: #00ccff;">Hello world</span>'
Answer to Question 2
I'm assuming that you mean taking an image from the web. Yes you can, but this is definitely a CSS/HTML related question. However following the same principle of my previous answer:
Picures taken from Unsplash
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
my_pic = 'https://images.unsplash.com/photo-1469980098053-382eb10ba017?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80'
return render_template('index.html', my_pic=my_pic)
if __name__ == '__main__':
app.run(debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body style="background-image: url(https://images.unsplash.com/photo-1600187734183-707cf1c0fd5a?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1304&q=80);"
>
< <div>
<h1 style="color: white;">Picture from HTML</h1>
<img src="https://images.unsplash.com/photo-1600298881979-9b0c50d7abdf?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=400&q=60" alt="opps">
</div>
<div style="color: white;">
<h1>Picture from Flask</h1>
<img src="{{my_pic}}" alt="oops">
</div>
</body>
</html>
I suggest you to learn it from HTML and CSS related topic rather than Flask (first learn some CSS and HTML basic):
CSS
HTML
That been said I have a more interesting a USEFUL answer that however requires basic knowledge of the use of a Database, I assume you are a beginner and you may have not yet this knowledge but soon or later you will. So even if you dont understand completely the following keep it in mind and come back later.
I prepared a mini app that using flask, flask_sqlalchemy (with sqlite3), html and Bootstrap.
This app does the following and will teach you these principle:
.1 Upload a picture into a Database.
.2 How to download a picture from the Database.
.3 Render the picture from the Database into the WebBroser.
FULL CODE FROM GITHUB
Some Code from this mini app
Initiate the database, configs and Picture table for the databse
In class FileContent(db.Model):
data = file.read() It saves in database the Binary version of thefile
-render_file = render_picture(data). It saves the decode version, so that you can you see it for render it in the webpages.
# Built-in Imports
import os
from datetime import datetime
from base64 import b64encode
import base64
from io import BytesIO #Converts data from Database into bytes
# Flask
from flask import Flask, render_template, request, flash, redirect, url_for, send_file # Converst bytes into a file for downloads
# FLask SQLAlchemy, Database
from flask_sqlalchemy import SQLAlchemy
basedir = 'sqlite:///' + os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data.sqlite')
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = basedir
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'dev'
db = SQLAlchemy(app)
# Picture table. By default the table name is filecontent
class FileContent(db.Model):
"""
The first time the app runs you need to create the table. In Python
terminal import db, Then run db.create_all()
"""
""" ___tablename__ = 'yourchoice' """ # You can override the default table name
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(128), nullable=False)
data = db.Column(db.LargeBinary, nullable=False) #Actual data, needed for Download
rendered_data = db.Column(db.Text, nullable=False)#Data to render the pic in browser
text = db.Column(db.Text)
location = db.Column(db.String(64))
pic_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
def __repr__(self):
return f'Pic Name: {self.name} Data: {self.data} text: {self.text} created on: {self.pic_date} location: {self.location}'
Upload route, here is where the picture its sent to databse and processed with correct data
So here is what is going on in the app route:
def render_picture(data) --> Takes the bites raw version of the pic and return the decode version, so that it can be used to be display on the web.
data = file.read() : This is the raw data.This can be used for downloading the pic from database
render_file: decoded file so you can retrieve it and the render in the web page
#Render the pics, this Function converts the data from
request.files['inputFile'] so that in can be displayed
def render_picture(data):
render_pic = base64.b64encode(data).decode('ascii')
return render_pic
#app.route('/upload', methods=['POST'])
def upload():
file = request.files['inputFile']
data = file.read()
render_file = render_picture(data)
text = request.form['text']
location = request.form['location']
newFile = FileContent(name=file.filename, data=data,
rendered_data=render_file, text=text, location=location)
db.session.add(newFile)
db.session.commit()
flash(f'Pic {newFile.name} uploaded Text: {newFile.text} Location:
{newFile.location}')
return render_template('upload.html')
INDEX Route
# Index It routes to index.html where the upload forms is
#app.route('/index', methods=['GET', 'POST'])
#app.route('/')
def index():
return render_template('index.html')
INDEX HTML with the Form
<form method="POST" action="/upload" enctype="multipart/form-data">
<!-- File Upload-->
<div class="form-group">
<label for="inputFile">File input</label>
<input class="form-control-file" type="file" name="inputFile">
</div>
<!-- Location -->
<div class="form-group">
<label for="location">Location</label>
<input class="form-control" type="text" name="location">
</div>
<!-- Text -->
<div class="form-group">
<label for="text">Write Text</label>
<textarea class="form-control" name="text" id="text" rows="5" placeholder="Add a Description"></textarea>
</div>
<!-- Submit -->
<button type="submit" class="btn btn-primary">Submit</button>
</form>

jinja2.exceptions.TemplateSyntaxError: expected token 'end of print statement', got '='

Respected Members,
I'm creating a basic login page sans the DB setup. I'm not sure what I'm doing wrong while passing the jinja templates to the html file.
The .py file:
from flask import Flask, render_template, flash, session, redirect, url_for
from flask_wtf import FlaskForm
from wtforms import StringField,SubmitField
from wtforms.validators import DataRequired
app = Flask(__name__)
app.config['SECRET_KEY'] = 'kmykey'
class SimpleForm(FlaskForm):
username = StringField("Username:", validators=[DataRequired()])
password = StringField("Password:", validators=[DataRequired()])
submit = SubmitField("Submit")
#app.route('/', methods = ['GET', 'POST'])
def index():
form = SimpleForm()
if form.validate_on_submit():
session['username'] = form.username.data
session['password'] = form.password.data
return redirect(url_for('index'))
return render_template('Login_Page1.html', form=form)
if __name__ == '__main__':
app.run()
The html file:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Ticket Booking</title>
<link rel="stylesheet" type= "text/css" href=" {{ url_for('static',filename='Login_Page1.css') }}">
<link href="https://fonts.googleapis.com/css2?family=Anton&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<!-- JS, Popper.js, and jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</head>
<body>
<div align="center" class="main1">
<form method="POST">
<h1>Railway Booking Portal</h1>
<h2>Welcome!</h2>
<br>
{# This hidden_tag is a CSRF security feature. #}
{{ form.hidden_tag() }}
{{ form.username.label, extra_classes='uname1' }} {{ form.username(placeholder='email here') }}
<br>
{{ form.password.label, extra_classes='passwd1' }} {{ form.password}}
<br>
<a class="abc" href="Sign_Up.html"><u>SignUp</u></a>
<br>
<a class="abc1" href="Password_Reset.html"><u>ForgotPassword</u></a>
<br>
<br>
{{ form.submit() }}
<br>
<p>"One's destination is never a place, but a new way of seeing things." - Henry Miller</p>
</form>
</div>
The css file:
body{
background: url(railway-tracks.jpeg);
background-repeat: no-repeat;
}
h1{
color: black;
}
p{
font-family: 'Anton', sans-serif;
font-size: 200%;
color: black;
}
.uname1{
display: inline-block;
min-width: 90px;
color: red;
}
.passwd1{
display: inline-block;
min-width: 90px;
color: red;
}
.main1{
background-color: rgba(255, 255, 255, 0.6);
}
.abc{
color: black;
}
.abc1{
color: black;
}
Kindly guide, what is the part that I've done wrong.
I also tried inject the wtf form's attributes to html via (also used class instead of class_):
{{ form.username.label(class_='uname') }} {{ form.username(placeholder='email here') }}
{{ form.password.label(class_='passwd') }} {{ form.password}}
Although didn't receive an error, and successfully flask app ran and the page was shown with all relevant syling/formatting, but the labels weren't formatted.
You can see the answer here
Updated for WTForms 2.1
You can now as of WTForms 2.1 (December 2015) set rendering keywords by using the render_kw= parameter to the field constructor.
So the field would look like:
abc = StringField('abc', [InputRequired()], render_kw={"placeholder": "test"})
(Old answer, still true for versions older than WTForms 2.1)
placeholder is not supported in the Python constructor in WTforms 2.0.x and below.
However, you can do this easily in your template:
{{ form.abc(placeholder="test") }}
You can see the answer here
Change code, i use pycharm and see that
{{ form.username.label(extra_classes='uname1') }} {{ form.username(placeholder='email here') }}
<br>
{{ form.password.label(extra_classes='passwd1') }} {{ form.password}}
Updated for WTForms 2.1
You can now as of WTForms 2.1 (December 2015) set rendering keywords by using the render_kw= parameter to the field constructor.
So the field would look like:
abc = StringField('abc', [InputRequired()], render_kw={"placeholder": "test"})
(Old answer, still true for versions older than WTForms 2.1)
placeholder is not supported in the Python constructor in WTforms 2.0.x and below.
However, you can do this easily in your template:
{{ form.abc(placeholder="test") }}

How to add images in CSS file? I am using python flask for website development

Everything was working fine before Python Flask. Now I tried to connect my HTML page with Python Flask. CSS is working fine but when I define images inside the CSS file the image is no longer loaded into the web site. Instead it is showing error 404.
python app.py code
from flask import Flask, render_template, url_for
app = Flask(__name__ , static_url_path='/static')
#app.route('/')
def index():
return render_template('/intro.html')
if __name__ == '__main__':
app.run(debug=True)
HTML code :-
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width-device-width, initial-scale=1.0">
<title>NewliFit</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://unpkg.com/aos#next/dist/aos.css" />
<link rel="stylesheet" href="{{ url_for('static',filename='css/owl.carousel.css') }}">
<link rel="stylesheet" href="{{ url_for('static',filename='css/owl.carousel.min.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename = 'css/owl.theme.default.css') }}">
<link rel="stylesheet" href="{{ url_for('static',filename='css/firstone.css') }}">
</head>
<body>
<div class="main">
<div class="cover-image">
<div class="menu">
<div class="leftmenu">
CSS file
#charset "utf-8";
/* CSS Document */
*{
margin: 0px ;
padding: 0px ;
}
/* ------------cover image -------------*/
.cover-image {
background-image: url({{ url_for('static',filename = '/images/cover4.jpg')}});
background-size: 100% 100%;
width: 100%;
height: 110vh;
}
Please help.
You are using url_for in a CSS file, which does not work. You need to specify the url of the background image either in the HTML file, or specify a proper URL in your CSS.
So either add this to your CSS:
background-image: url('/static/images/cover4.jpg')}});
Or change your cover-image div in your HTML file to this:
<div class="cover-image" style="background-image: url({{ url_for('static',filename = '/images/cover4.jpg')}});">
Unless you plan on changing your static folder (or your cover image) regularly, I would advise going the first route, to make sure you separate style and semantics.

Loading URLs into an iFrame using Flask

I'm new to Flask and
I'm trying to create a Stumbleupon like website but I'm having problems while loading the content into an iFrame. I just cant figure it out how to iterate through each url and load them into the iFrame while clicking in the <a> tag.
Here is what I've done:
app.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def index():
urls = [
'http://www.w3schools.com',
'http://techcrunch.com/',
'https://www.fayerwayer.com/',
]
return render_template('index.html', urls=urls)
if __name__ == "__main__":
app.run(debug=True)
templates/layout.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="/static/css/normalize.css"/>
<link rel="stylesheet" type="text/css" href="/static/css/foundation.css"/>
</head>
<body>
<nav class="top-bar">
<h3 align="center">Stumble</h3>
</nav>
{% block content %}
{% endblock content %}
</body>
</html>
templates/index.html
{% extends 'layout.html' %}
{% block content %}
<iframe frameborder='0' noresize='noresize' style='position: absolute; background: transparent; width: 100%; height:100%;' src="????????" frameborder="0"></iframe>
{% endblock content %}
After adding import random at the top of your app.py file you could structure your code like this:
def index():
urls = [
'http://www.w3schools.com',
'http://techcrunch.com/',
'https://www.fayerwayer.com/',
]
iframe = random.choice(urls)
return render_template('index.html', iframe=iframe)
Then access the value in your template:
<iframe frameborder='0' noresize='noresize' style='position: absolute; background: transparent; width: 100%; height:100%;' src="{{ iframe }}" frameborder="0"></iframe>
And simply set the Stumble button to refresh the page.
<h3 align="center">Stumble</h3>
This will be pretty basic, but it will have the behaviour you're describing.
An improvement will be to use the session object to make sure that two subsequent requests do not display the same page inside the iframe.

Categories