Re-Ask: Whats wrong with the Flask-Bootstrap? - python

OK
So you didn't like my last question
Here is a SECOND question, with much more information than actually needed. It's a very simple problem defining the base dir inside the flask-bootstrap module. If you managed to see my last question, I showed my code, but here is some more of the USELESS information you wanted for some odd reason:
Index.html
{% extends 'bootstrap/base.html' %}
<!-- TEST THINGS ON A DIFFERENT REPL! -->
<!DOCTYPE html>
<html>
<head>
<!-- This is for the tab -->
<title>Helliott-chip</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<link href="{{ url_for('static', filename='style.css') }}" rel="stylesheet" type="text/css" />
</head>
<body>
<!-- Title on top -->
<h1><center>Helliot-Chip</center></h1>
<p>New User? Click to Register!</p>
<!-- Grey Menu Select -->
<div class="scrollmenu1">
{% if current_user.is_anonymous %}
Login
{% else %}
Logout
Profile
{% endif %}
Home
About
Explore
Videos
Music
</div>
{% block content %}
<h1>Hi, {{ current_user.username }}!</h1>
{% endblock %}
{% block app_content %}{% endblock %}
{% block scripts %}
{{ super() }}
{{ moment.include_moment() }}
{% endblock %}
</body>
</html>
init.py
import logging
from logging.handlers import SMTPHandler, RotatingFileHandler
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from config import Config
from flask_mail import Mail
from flask_bootstrap import Bootstrap
from flask_moment import Moment
app = Flask(__name__)
Bootstrap(app)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
login = LoginManager(app)
login.login_view = 'login'
mail = Mail(app)
moment = Moment(app)
from app import models, errors
So now that I have that down, my error (after I changed the index to base in the index.html):
[2021-04-13 17:18:39,365] INFO in debughelpers: Locating template "index.html":
1: trying loader of application "app"
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /home/runner/Website30/app/templates
-> found ('/home/runner/Website30/app/templates/index.html')
2: trying loader of blueprint "bootstrap" (flask_bootstrap)
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /opt/virtualenvs/python3/lib/python3.8/site-packages/flask_bootstrap/templates
-> no match
[2021-04-13 17:18:39,372] INFO in debughelpers: Locating template "bootstrap/base.html":
1: trying loader of application "app"
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /home/runner/Website30/app/templates
-> no match
2: trying loader of blueprint "bootstrap" (flask_bootstrap)
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /opt/virtualenvs/python3/lib/python3.8/site-packages/flask_bootstrap/templates
-> found ('/opt/virtualenvs/python3/lib/python3.8/site-packages/flask_bootstrap/templates/bootstrap/base.html')
172.18.0.1 - - [13/Apr/2021 17:18:39] "GET / HTTP/1.1" 200 -
[2021-04-13 17:18:40,173] INFO in debughelpers: Locating template "404.html":
1: trying loader of application "app"
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /home/runner/Website30/app/templates
-> found ('/home/runner/Website30/app/templates/404.html')
2: trying loader of blueprint "bootstrap" (flask_bootstrap)
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /opt/virtualenvs/python3/lib/python3.8/site-packages/flask_bootstrap/templates
-> no match
And my error before I changed it:
jinja2.exceptions.TemplateNotFound: bootstrap/index.html
Now this time without having my question being shut down from any answers in general (which I may note is opposing the purpose of this site) What would be wrong here? Is something wrong with the way I'm initializing flask-bootstrap, or is there some command I need to put in the terminal? Feel free to ask questions, and thanks a lot if it's a simple problem I'm missing. And I apologize for any unneeded attitude, I was just disappointed in the person who locked my last question for "not enough information".

There is an issue with the way you are initializing flask-bootstrap. This how you should go about it:
# Your previous imports
from flask_bootstrap import Bootstrap
app = Flask(__name__)
bootstrap = Bootstrap(app)
# ...
Basically, update the line:
Bootstrap(app)
to:
bootstrap = Bootstrap(app)
This is exactly what you have done for the other installed packages too.
Maintain the line {% extends 'bootstrap/base.html' %} in your base template (which is the parent template). Do not change it to {% extends 'bootstrap/index.html' %} This file inherits the styles, layout, features etc from bootstrap's base template.
<!-- base.html -->
{% extends 'bootstrap/base.html' %}
{% block head %}
<!-- Head information goes here -->
{% endblock %}
{% block navbar %}
<!-- Your navbar goes here -->
{% endblock %}
{% block content %}
<!-- flash message goes here -->
{% block app_content %}
<!-- Content from your custom HTML templates will go here -->
{% endblock %}
{% endblock %}
{% block scripts %}
<!-- Your scripts go here -->
{% endblock %}
In your index.html file which inherits your base,html, you will do:
<!-- index.html -->
{% extends 'base.html' %}
{% block app_content %}
<!-- Content goes here -->
{% endblock %}

Related

Strip unwanted html entieties

I'm upgrading mezzanine/django application from Mezzanine4.x/python2.7 to Mezzanine5.0/python3.7. My HTML page has been created using templatetags. Now the upgaraded page shows unwanted html entieties when checked with browser's (Firefox or Chrome) view page source feature. In python 2.7 it looks like
<p><a href='/'>Etusivu</a> > Ajankohtaista</p>
whereas in python 3.7 it shows
<p><a href='/'>Etusivu tags1</a> > Ajankohtaista</p>
these unwanted entieties are not seen with browser's inspect element feature.
from html:
<!doctype html>
{% load pages_tags mezzanine_tags i18n future staticfiles statfi_tags %}
<body id="{% block body_id %}body{% endblock %}">
{% block base %}
<div id="container">
<main id="page">
<div class="row">
<div id="breadcrumbs" class="col-xs-7 col-sm-8 col-md-9 col-lg-10">
{% block breadcrumbs %}
{% if page.basicpage %}
<p>{% anna_murut page.basicpage %}</p>
{% endif %}
{% endblock %}
</div>
</div>
{% endblock %}
</main>
</div>
{% endblock %}
</body>
</html>
from statfi_tags.py
# -*- coding: utf-8 -*-
from django import template
from datetime import date
from page_types import models
from django.db import models
from django.contrib.sites.models import Site
from django.template import Context, RequestContext
from django.template import Library, Node
from page_types.models import BasicPage, RegisterDescPage
from mezzanine.pages.models import Page, Link
from django.utils.encoding import *
register = template.Library()
def anna_murut(BasicPage):
sivu = BasicPage
letka = letka = u"<a href='/'>Etusivu</a> > "
if not "/" + BasicPage.slug == site_url(BasicPage):
letka += u"<a href='"+ site_url(BasicPage) +"'>"+ str(paasite(BasicPage)) +"</a> > "
letka += BasicPage.title
return letka
register.simple_tag(anna_murut)
Python 2.7-version in browser:
Python 3.7-version in browser:
Any ideas how to fix python 3.7 version? I don't know it it could be fixed in python code as the unwanted entities are note seen when I print the string returned by function "anna_murut".
The newer Django versions mark simple tags as unsafe by default, that means they may contain user submitted harmful code, therefore Django will escape any "dangerous" HTML tag.
You have to mark explicitly any string returned by custom tags as safe in order to avoid the default escaping.
from django.utils.safestring import mark_safe
def anna_murut(BasicPage):
# ...
return mark_safe(letka)
Just make sure that letka does not contain any unescaped user-submitted content.

Not able to display content on webpage using flask

Need some help, not getting the content from the database not sure why this is happening
using python flask,sqlalchemy with a small sqlite database
I need to see the content from the database displayed on the web page.
At the moment I see only the Home link which is static in the template file.
app.py contains a part of this
#app.route('/page/<int:page_id>')
def view_page(page_id):
page = db.session.query(Pages).filter_by(id=page_id).first()
return render_template('page.html', id=page.id, title=page.title.decode(),
content=page.content.decode())
page.html (this is the template)
{% extends "master.html" %}
{% block content %}
<!DOCTYPE html>
{% for page in pages %}
<h3>{{ page.title.decode() |truncate(150)}}
</h3></a>
<p>{{ page.content.decode() |safe | truncate(350) }}</p>
{% endfor %}
Home
{% endblock %}
</html>
You have to send model with your return template.
#app.route('/page/<int:page_id>')
def view_page(page_id):
pages = Pages.query.all()
return render_template('page.html', pages=pages)

render_template HTML renders but variables not evaluated

I am trying to build an "enterprise grade" version of a flask app so am using blueprints and a fancy directory structure. I have a "toy" version of this app where everything is in a very flat directory structure with no blueprints and it works.
I have a route program that calcs some variables then passes them to render_template to generate html. The html displays in the browser but all of the variables appear to be set to NONE.
My app uses blueprints and SQLite3.
I have tried multiple things to isolate the error.
Make a textual change to html template to ensure the right template is being picked up. It is.
Pass trivial string variable to html template and see if they show up, they don't.
View source of rendered html, there is nothing where the flask variable names {{ x }} occur in the html template, including the {{ x }} text itself. So it appears the value None has been been used.
Test the code leading up to the render_template, it works perfectly.
My directory structure is: -
\myapp
app.py
\app
__init__.py
\main
__init__.py
routes.py
...
\meta
__init__.py
routes.py
...
\templates
...
base.html
index.html
The code in \meta\routes.py (which corresponds to the meta blueprint) works down to and including entitys = stmt.fetchall() and is: -
from flask import Flask, render_template, request
import sqlite3 as sql
from app.meta import bp
from app import Config
config = Config()
metafile = os.path.join(config.META_DIR, config.META_MS, config.META_DB)
#bp.route('/', methods=['GET', 'POST'])
#bp.route('/index', methods=['GET', 'POST'])
def index():
meta = sql.connect(metafile)
stmt = meta.cursor()
stmt.execute("SELECT * FROM [meta.Entity]")
entitys = stmt.fetchall()
return render_template("index.html", entitys = entitys)
In case it is relevant here is \meta\__init__.py: -
from flask import Blueprint
bp = Blueprint('meta', __name__)
The template html is as follows. The base.html is: -
<!doctype html>
<html>
<head>
{% if title %}
<title>{{ title }} - Metapplica</title>
{% else %}
<title>Metapplica</title>
{% endif %}
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="{{ url_for('static', filename = 'w3.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename = 'style.css') }}">
</head>
<body>
<div>
Home
</div>
<hr>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
{% block content %}{% endblock %}
</body>
</html>
and index.html is: -
{% extends "base.html" %}
{% block content %}
<h2>Entities</h2>
<table border = 1>
<thead>
<td>Entity</td>
<td>Action</td>
</thead>
{% for entity in entitys %}
<tr>
<td>{{ entity["Name"] }}</td>
<td>
List
Add
</td>
</tr>
{% endfor %}
</table>
{% endblock %}
Finally the rendered html is this: -
<!doctype html>
<html>
<head>
<title>Home - Metapplica</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/static/w3.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<div>
Home
</div>
<hr>
<h2>Entities </h2>
<table border = 1>
<thead>
<td>Entity</td>
<td>Action</td>
</thead>
</table>
</body>
</html>
In response to #Tobin's comment I have included the code that (should) be registering the blueprint. I use an application factory.
Here is app\__init__()
import logging
from logging.handlers import SMTPHandler, RotatingFileHandler
import os
from flask import Flask, session, redirect, url_for, escape, request, current_app
from config import Config
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
# Register blueprints
from app.errors import bp as errors_bp
app.register_blueprint(errors_bp, url_prefix='/err')
from app.auth import bp as auth_bp
app.register_blueprint(auth_bp, url_prefix='/auth')
from app.meta import bp as meta_bp
app.register_blueprint(meta_bp, url_prefix='/meta')
from app.main import bp as main_bp
app.register_blueprint(main_bp)
return app
and here is the code that calls it: -
from app import create_app
app = create_app()
I suspect that somehow when Flask renders the html template the passed variables are not available to the "flask engine" which is pointing somewhere else.
Nothing fails and there are no error messages.
What am I doing wrong?

flask isnt reading or interpreting css file

I'm basically trying to follow this tutorial ( http://net.tutsplus.com/tutorials/python-tutorials/an-introduction-to-pythons-flask-framework/)
Now when the css part comes in, and i copy the code it simply wont come out styled even afterr main.css is added it still shows up unstyled like if it wasn't importing the css file here's the HTML code
<!DOCTYPE html>
<html>
<head>
<title>Flask</title>
<strong><link rel="stylesheet" type"text/css" href="{{ url_for('static', filename='css/main.css') }}"></strong>
</head>
<body>
<header>
<div class="container">
<h1 class="logo">Flask App</h1>
</div>
</header>
<div class="container">
{% block content %}
{% endblock %}
</div>
</body>
</html>
layout.html ^
Home.html v
{% extends "layout.html" %}
{% block content %}
<div class="jumbo">
<h2>Welcome to the Flask app<h2>
<h3>This is the home page for the Flask app<h3>
</div>
{% endblock %}
routes.py v
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def home():
return render_template('home.html')
if __name__ == '__main__':
app.run(debug=True)
This is probably due to the directory structure of your app. By default, flask looks for the static directory in the same level as the file that the app object is created in. This is the example structure for a small application from the flask docs.
/yourapplication
/yourapplication.py
/static
/style.css
/templates
layout.html
index.html
login.html
You can also change the location of the static files by setting the "static_folder" attribute on the app object. Check the docs here for setting the static_folder

why is GAE not finding the files in my templates folder?

I'm so confused. The thing worked fine last night and all of a sudden today stopped working.
The purpose of this page is to generate a list of colors. The templates are located in their own folder called "templates", but GAE can't seem to find these templates at all.
What am I doing wrong here?
main2.py:
import bottle
from bottle import static_file
from google.appengine.ext.webapp import util
from bottle import route
# Load the template system
from jinja2 import Environment, FileSystemLoader
# Indicate from where the templates will be loaded
env = Environment(loader=FileSystemLoader('./templates/'))
# for randomly picking colors
import random
colors = 'green red blue';
#route('/favicon.ico')
def send_image():
filename = 'favicon.ico'
return static_file(filename, root='./images/', mimetype='image/ico');
#route('/hello')
def hello():
template = env.get_template('home.html');
color_list = colors.split();
num_colors = random.randint(0,len(color_list)+1);
color_list = color_list[:num_colors];
return template.render(title="Color List Page!", color_list=color_list);
util.run_wsgi_app(bottle.default_app())
app.yaml
application: yao-webapp2
version: 1
api_version: 1
runtime: python
handlers:
- url: .*
script: main2.py
/templates/base.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>
{% block title %}
I am stupid as heck: I forgot to fill in a title.
{% endblock %}
</title>
</head>
<body>
{% block content %}
No body knows the trouble I've seen.
{% endblock %}
</body>
</html>
/templates/home.html
{% extends "base.html" %}
{% block title %}
{{page_title}}
{% endblock %}
{% block content %}
<h1>Some Colors I know </h1>
<p>I have a list of colors that I know</p>
{% if color_list %}
<ul>
{% for color in color_list %}
<li> {{ color }} </li>
{% endfor %}
</ul>
{% else %}
<p>Oops! No colors.</p>
{% endif %}
{% endblock %}
not sure what error you are getting but i would try to use absolute paths.
instead of
env = Environment(loader=FileSystemLoader('./templates/'))
try to use this code:
templatespath = os.path.join(os.path.dirname(__file__), "templates")
env = Environment(loader=FileSystemLoader(templatespath))

Categories