SlideShare a Scribd company logo
1 of 22
Download to read offline
Flask Templates 
(aka Jinja2) 
by @alanhamlett
Blocks ( templates/common/base.html ) 
Blocks name parts of your template, and can be re-used in child templates. 
<html> 
<title>{% block title %}My Website{% endblock %}</title> 
<body> 
{% block body %} 
{% endblock %} 
</body> 
</html>
Inheritance ( templates/login.html ) 
{% extends "common/base.html" %} 
{% block title %}super() - Login{% endblock %} 
{% block body %} 
<form method="POST"> 
<p><input type="text" name="username" /></p> 
<p><input type="password" name="password" /></p> 
<p><button type="submit">Login</button></p> 
</form> 
{% endblock %}
Variable Scope ( templates/common/base.html ) 
<html> 
<title>{% block title %}My Website{% endblock %}</title> 
<body> 
{% with %} 
{% set variable = "value" %} 
{% block body %} 
{% endblock %} 
{% endwith %} 
</body> 
</html>
Variable Scope ( templates/login.html ) 
{% extends "common/base.html" %} 
{% block title %}super() - Login{% endblock %} 
{% block body %} 
<form method="POST"> 
<p><input type="hidden" name="variable" value="{{variable}}" /></p> 
<p><input type="text" name="username" /></p> 
<p><input type="password" name="password" /></p> 
<p><button type="submit">Login</button></p> 
</form> 
{% endblock %}
Rendering Templates ( __init__.py ) 
from flask import Flask 
app = Flask(__name__) 
from flask import render_template 
@app.route("/login") 
def login(): 
return render_template('login.html') 
if __name__ == "__main__": 
app.run()
Rendering Templates ( __init__.py ) 
from flask import Flask 
app = Flask(__name__) 
from . import views 
if __name__ == "__main__": 
app.run()
Rendering Templates ( views.py ) 
from . import app 
from flask import render_template 
@app.route("/login") 
def login(): 
context = { 
'features': [ 
{'icon': 'free.png', 'name': 'Free'}, 
{'icon': 'easy.png', 'name': 'Easy'}, 
{'icon': 'powerful.png', 'name': 'Powerful'}, 
], 
} 
return render_template('login.html', **context)
Rendering Variables ( templates/login.html ) 
{% extends "common/base.html" %} 
{% block title %}super() - Login{% endblock %} 
{% block body %} 
<h1>Included Features:</h1> 
<ul> 
{% for feature in features %} 
<li><img src="{{STATIC_URL}}img/icons/{{feature.icon}}" /> {{feature.name}}</li> 
{% endfor %} 
</ul> 
<form method="POST"> 
<p><input type="text" name="username" /></p> 
<p><input type="password" name="password" /></p> 
<p><button type="submit">Login</button></p> 
</form> 
{% endblock %}
Filters ( templates/login.html ) 
{% extends "common/base.html" %} 
{% block title %}super() - Login{% endblock %} 
{% block body %} 
<h1>Included Features:</h1> 
<ul> 
{% for feature in features %} 
<li><img src="{{STATIC_URL}}img/icons/{{feature.icon}}" /> {{feature.name|lower}}</li> 
{% endfor %} 
</ul> 
<form method="POST"> 
<p><input type="text" name="username" /></p> 
<p><input type="password" name="password" /></p> 
<p><button type="submit">Login</button></p> 
</form> 
{% endblock %}
Flask-WTF ( forms.py ) 
from flask.ext.wtf import Form 
from wtforms import StringField, PasswordField 
from wtforms.validators import DataRequired, Email, Length 
class LoginForm(Form): 
username = StringField('name', validators=[DataRequired(), Email()]) 
username = PasswordField('name', validators=[DataRequired(), Length(min=6)])
Flask-WTF ( views.py ) 
from . import app 
from .forms import LoginForm 
from flask import render_template, request 
@app.route("/login", methods=('GET', 'POST')) 
def login(): 
form = LoginForm(request.form) 
if request.method == 'POST' and form.validate(): 
return redirect('/myprofile') 
return render_template('login.html', form=form)
Flask-WTF ( templates/login.html ) 
{% extends "common/base.html" %} 
{% block title %}super() - Login{% endblock %} 
{% block body %} 
<form method="POST"> 
<p>Username <input type="text" name="username" value="{{form.data.username or ''}}" /></p> 
<p>Password <input type="password" name="password" value="{{form.data.password or ''}}" /></p> 
<p><button type="submit">Login</button></p> 
</form> 
{% endblock %}
Flask-WTF ( templates/login.html ) 
... 
{% block body %} 
<form method ="POST" > 
{% for field in form._fields.values() %} 
< div class="form-group" > 
{{ field.label(class="col-sm-3 control-label") }} 
< div class="col-sm-6 col-md-4" > 
{{ field(class="form-control") }} 
{% for error in field.errors %} 
< p>{{error}}</ p> 
{% endfor %} 
</ div> 
</ div> 
{% endfor %} 
< div class="form-group" > 
< div class="col-sm-6 col-md-4 col-sm-offset-3" > 
< button type="submit" >Login</ button > 
</ div> 
</ div> 
</ form> 
{% endblock %} 
...
Flask-Admin
Flask-Admin ( admin.py ) 
from . import app 
from .models import db, User 
from flask.ext.admin import Admin 
from flask.ext.admin.contrib.sqla import ModelView 
admin = Admin(app) 
admin.add_view(ModelView(User, db.session))
Flask-Admin ( __init__.py ) 
from flask import Flask 
app = Flask(__name__) 
from . import views 
from . import admin 
if __name__ == "__main__": 
app.run()
Flask-Admin 
Extend these Flask-Admin classes to protect your Admin pages: 
● flask.ext.admin.AdminIndexView 
● sqla.ModelView
Flask-Admin ( admin.py ) 
from . import app 
from .models import db, User 
from flask.ext.admin import Admin, AdminIndexView as UnsafeAdminIndexView, expose 
from flask.ext.admin.contrib.sqla import ModelView 
class AdminIndexView(UnsafeAdminIndexView): 
@expose('/') 
def index(self): 
if not app.current_user.is_authenticated(): 
return redirect('/login') 
if not app.current_user.is_admin: 
abort(403) 
return super(AdminIndexView, self).index() 
@expose('/login/') 
def login_view(self): 
return redirect('/login') 
@expose('/logout/') 
def logout_view(self): 
return redirect('/logout') 
admin = Admin(app, index_view=AdminIndexView(), template_mode='bootstrap3', base_template='admin/custom_base.html') 
admin.add_view(ModelView(User, db.session))
Flask-Admin ( admin.py ) 
... 
class ModelView(sqla.ModelView): 
edit_template = 'admin/model/edit.html' 
create_template = 'admin/model/create.html' 
list_template = 'admin/model/custom_list.html' 
def __init__(self, *args, **kwargs): 
if 'exclude' in kwargs: 
self.form_excluded_columns = kwargs['exclude'] 
del kwargs['exclude'] 
if 'show' in kwargs: 
self.column_list = kwargs['show'] 
del kwargs['show'] 
pass_through = [ 
'can_create', 
'can_edit', 
'can_delete', 
] 
for item in pass_through: 
if item in kwargs: 
setattr(self, item, kwargs[item]) 
del kwargs[item] 
super(ModelView, self).__init__(*args, **kwargs) 
def is_accessible(self): 
return app.current_user.is_authenticated() and app.current_user.is_admin 
admin.add_view(ModelView(User, db.session, category='Users', exclude=['password', 'heartbeats'], can_delete=False)) 
...
Now go build something cool! 
Alan Hamlett 
@alanhamlett on Twitter & GitHub 
alan@wakatime.com 
View this online at 
http://slidesha.re/1wfDzrv

More Related Content

What's hot

Ruby on Rails : RESTful 和 Ajax
Ruby on Rails : RESTful 和 AjaxRuby on Rails : RESTful 和 Ajax
Ruby on Rails : RESTful 和 AjaxWen-Tien Chang
 
Desenvolvimento web com Ruby on Rails (parte 6)
Desenvolvimento web com Ruby on Rails (parte 6)Desenvolvimento web com Ruby on Rails (parte 6)
Desenvolvimento web com Ruby on Rails (parte 6)Joao Lucas Santana
 
Django Templates
Django TemplatesDjango Templates
Django TemplatesWilly Liu
 
Cordova training : Day 6 - UI development using Framework7
Cordova training : Day 6 - UI development using Framework7Cordova training : Day 6 - UI development using Framework7
Cordova training : Day 6 - UI development using Framework7Binu Paul
 
Django Admin: Widgetry & Witchery
Django Admin: Widgetry & WitcheryDjango Admin: Widgetry & Witchery
Django Admin: Widgetry & WitcheryPamela Fox
 
Ch9 .Best Practices for Class-Based Views
Ch9 .Best Practices  for  Class-Based ViewsCh9 .Best Practices  for  Class-Based Views
Ch9 .Best Practices for Class-Based ViewsWilly Liu
 
Slimme Joomla! Templating Tips en Truuks
Slimme Joomla! Templating Tips en TruuksSlimme Joomla! Templating Tips en Truuks
Slimme Joomla! Templating Tips en TruuksThemePartner
 
Curso Symfony - Clase 3
Curso Symfony - Clase 3Curso Symfony - Clase 3
Curso Symfony - Clase 3Javier Eguiluz
 
HTML::FormFu talk for Sydney PM
HTML::FormFu talk for Sydney PMHTML::FormFu talk for Sydney PM
HTML::FormFu talk for Sydney PMDean Hamstead
 
Introduction to UI Components in Magento 2
Introduction to UI Components in Magento 2Introduction to UI Components in Magento 2
Introduction to UI Components in Magento 2Sergii Ivashchenko
 
Empowering users: modifying the admin experience
Empowering users: modifying the admin experienceEmpowering users: modifying the admin experience
Empowering users: modifying the admin experienceBeth Soderberg
 
Bootstrap day4
Bootstrap day4Bootstrap day4
Bootstrap day4Shais. Net
 
QCon 2015 - Thinking in components: A new paradigm for Web UI
QCon 2015 - Thinking in components: A new paradigm for Web UIQCon 2015 - Thinking in components: A new paradigm for Web UI
QCon 2015 - Thinking in components: A new paradigm for Web UIOliver Häger
 
Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2RORLAB
 
Improving state of M2 front-end - Magento 2 Community Project
Improving state of M2 front-end - Magento 2 Community ProjectImproving state of M2 front-end - Magento 2 Community Project
Improving state of M2 front-end - Magento 2 Community ProjectBartek Igielski
 

What's hot (20)

Jsf lab
Jsf labJsf lab
Jsf lab
 
Ruby on Rails : RESTful 和 Ajax
Ruby on Rails : RESTful 和 AjaxRuby on Rails : RESTful 和 Ajax
Ruby on Rails : RESTful 和 Ajax
 
iWebkit
iWebkitiWebkit
iWebkit
 
Desenvolvimento web com Ruby on Rails (parte 6)
Desenvolvimento web com Ruby on Rails (parte 6)Desenvolvimento web com Ruby on Rails (parte 6)
Desenvolvimento web com Ruby on Rails (parte 6)
 
Django Templates
Django TemplatesDjango Templates
Django Templates
 
Cordova training : Day 6 - UI development using Framework7
Cordova training : Day 6 - UI development using Framework7Cordova training : Day 6 - UI development using Framework7
Cordova training : Day 6 - UI development using Framework7
 
Intro to Haml
Intro to HamlIntro to Haml
Intro to Haml
 
Django Admin: Widgetry & Witchery
Django Admin: Widgetry & WitcheryDjango Admin: Widgetry & Witchery
Django Admin: Widgetry & Witchery
 
Django Bogotá. CBV
Django Bogotá. CBVDjango Bogotá. CBV
Django Bogotá. CBV
 
Ch9 .Best Practices for Class-Based Views
Ch9 .Best Practices  for  Class-Based ViewsCh9 .Best Practices  for  Class-Based Views
Ch9 .Best Practices for Class-Based Views
 
Slimme Joomla! Templating Tips en Truuks
Slimme Joomla! Templating Tips en TruuksSlimme Joomla! Templating Tips en Truuks
Slimme Joomla! Templating Tips en Truuks
 
Curso Symfony - Clase 3
Curso Symfony - Clase 3Curso Symfony - Clase 3
Curso Symfony - Clase 3
 
HTML::FormFu talk for Sydney PM
HTML::FormFu talk for Sydney PMHTML::FormFu talk for Sydney PM
HTML::FormFu talk for Sydney PM
 
Introduction to UI Components in Magento 2
Introduction to UI Components in Magento 2Introduction to UI Components in Magento 2
Introduction to UI Components in Magento 2
 
Empowering users: modifying the admin experience
Empowering users: modifying the admin experienceEmpowering users: modifying the admin experience
Empowering users: modifying the admin experience
 
Bootstrap day4
Bootstrap day4Bootstrap day4
Bootstrap day4
 
Stole16
Stole16Stole16
Stole16
 
QCon 2015 - Thinking in components: A new paradigm for Web UI
QCon 2015 - Thinking in components: A new paradigm for Web UIQCon 2015 - Thinking in components: A new paradigm for Web UI
QCon 2015 - Thinking in components: A new paradigm for Web UI
 
Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2
 
Improving state of M2 front-end - Magento 2 Community Project
Improving state of M2 front-end - Magento 2 Community ProjectImproving state of M2 front-end - Magento 2 Community Project
Improving state of M2 front-end - Magento 2 Community Project
 

Viewers also liked

Docker on ARM Raspberry Pi
Docker on ARM Raspberry PiDocker on ARM Raspberry Pi
Docker on ARM Raspberry PiEueung Mulyana
 
Rancher 快速打造叢集的解決方案
Rancher 快速打造叢集的解決方案Rancher 快速打造叢集的解決方案
Rancher 快速打造叢集的解決方案Miles Chou
 
Spring Boot and JHipster
Spring Boot and JHipsterSpring Boot and JHipster
Spring Boot and JHipsterEueung Mulyana
 
Docker Compose
Docker ComposeDocker Compose
Docker ComposeMiles Chou
 
Flask! - python web framework flask 튜토리얼
Flask! - python web framework flask 튜토리얼Flask! - python web framework flask 튜토리얼
Flask! - python web framework flask 튜토리얼mangonamu
 
Develop Desktop Apps with Electron
Develop Desktop Apps with ElectronDevelop Desktop Apps with Electron
Develop Desktop Apps with ElectronEueung Mulyana
 
Flask RESTful Flask HTTPAuth
Flask RESTful Flask HTTPAuthFlask RESTful Flask HTTPAuth
Flask RESTful Flask HTTPAuthEueung Mulyana
 
Deploying Containers with Rancher
Deploying Containers with RancherDeploying Containers with Rancher
Deploying Containers with RancherChris Tankersley
 
Rtl sdr software defined radio
Rtl sdr   software defined radioRtl sdr   software defined radio
Rtl sdr software defined radioEueung Mulyana
 
Consul and docker swarm cluster
Consul and docker swarm clusterConsul and docker swarm cluster
Consul and docker swarm clusterEueung Mulyana
 
Rancher meetup 20161007
Rancher meetup 20161007Rancher meetup 20161007
Rancher meetup 20161007Tetsurou Yano
 

Viewers also liked (17)

2d web mapping with flask
2d web mapping with flask2d web mapping with flask
2d web mapping with flask
 
Http basics
Http basicsHttp basics
Http basics
 
Openstack trystack
Openstack   trystack Openstack   trystack
Openstack trystack
 
Flask Basics
Flask BasicsFlask Basics
Flask Basics
 
Docker on ARM Raspberry Pi
Docker on ARM Raspberry PiDocker on ARM Raspberry Pi
Docker on ARM Raspberry Pi
 
Rancher 快速打造叢集的解決方案
Rancher 快速打造叢集的解決方案Rancher 快速打造叢集的解決方案
Rancher 快速打造叢集的解決方案
 
Spring Boot and JHipster
Spring Boot and JHipsterSpring Boot and JHipster
Spring Boot and JHipster
 
Docker Compose
Docker ComposeDocker Compose
Docker Compose
 
Flask! - python web framework flask 튜토리얼
Flask! - python web framework flask 튜토리얼Flask! - python web framework flask 튜토리얼
Flask! - python web framework flask 튜토리얼
 
Develop Desktop Apps with Electron
Develop Desktop Apps with ElectronDevelop Desktop Apps with Electron
Develop Desktop Apps with Electron
 
Flask RESTful Flask HTTPAuth
Flask RESTful Flask HTTPAuthFlask RESTful Flask HTTPAuth
Flask RESTful Flask HTTPAuth
 
Deploying Containers with Rancher
Deploying Containers with RancherDeploying Containers with Rancher
Deploying Containers with Rancher
 
Flask SQLAlchemy
Flask SQLAlchemy Flask SQLAlchemy
Flask SQLAlchemy
 
Learning kubernetes
Learning kubernetesLearning kubernetes
Learning kubernetes
 
Rtl sdr software defined radio
Rtl sdr   software defined radioRtl sdr   software defined radio
Rtl sdr software defined radio
 
Consul and docker swarm cluster
Consul and docker swarm clusterConsul and docker swarm cluster
Consul and docker swarm cluster
 
Rancher meetup 20161007
Rancher meetup 20161007Rancher meetup 20161007
Rancher meetup 20161007
 

Similar to Flask Templates, Inheritance, Forms, Admin

Intro to Jinja2 Templates - San Francisco Flask Meetup
Intro to Jinja2 Templates - San Francisco Flask MeetupIntro to Jinja2 Templates - San Francisco Flask Meetup
Intro to Jinja2 Templates - San Francisco Flask MeetupAlan Hamlett
 
引き出しとしてのDjango - SoozyCon7
引き出しとしてのDjango - SoozyCon7引き出しとしてのDjango - SoozyCon7
引き出しとしてのDjango - SoozyCon7makoto tsuyuki
 
Technical Preview: The New Shopware Admin
Technical Preview: The New Shopware AdminTechnical Preview: The New Shopware Admin
Technical Preview: The New Shopware AdminPhilipp Schuch
 
Flask intro - ROSEdu web workshops
Flask intro - ROSEdu web workshopsFlask intro - ROSEdu web workshops
Flask intro - ROSEdu web workshopsAlex Eftimie
 
Templates81 special document
Templates81 special documentTemplates81 special document
Templates81 special documentLan Nguyen
 
Templates81 special document
Templates81 special documentTemplates81 special document
Templates81 special documentLan Nguyen
 
TURN YOUR CELL PHONE FROM A LIABILITY INTO AN ASSET!
TURN YOUR CELL PHONE FROM A LIABILITY INTO AN ASSET!TURN YOUR CELL PHONE FROM A LIABILITY INTO AN ASSET!
TURN YOUR CELL PHONE FROM A LIABILITY INTO AN ASSET!Coulawrence
 
Djangoアプリのデプロイに関するプラクティス / Deploy django application
Djangoアプリのデプロイに関するプラクティス / Deploy django applicationDjangoアプリのデプロイに関するプラクティス / Deploy django application
Djangoアプリのデプロイに関するプラクティス / Deploy django applicationMasashi Shibata
 
Vue.js - zastosowanie i budowa komponentów
Vue.js - zastosowanie i budowa komponentówVue.js - zastosowanie i budowa komponentów
Vue.js - zastosowanie i budowa komponentówLaravel Poland MeetUp
 
Learning django step 1
Learning django step 1Learning django step 1
Learning django step 1永昇 陳
 
HTML5 New and Improved
HTML5   New and ImprovedHTML5   New and Improved
HTML5 New and ImprovedTimothy Fisher
 
Vaadin Components @ Angular U
Vaadin Components @ Angular UVaadin Components @ Angular U
Vaadin Components @ Angular UJoonas Lehtinen
 
Private slideshow
Private slideshowPrivate slideshow
Private slideshowsblackman
 

Similar to Flask Templates, Inheritance, Forms, Admin (20)

Intro to Jinja2 Templates - San Francisco Flask Meetup
Intro to Jinja2 Templates - San Francisco Flask MeetupIntro to Jinja2 Templates - San Francisco Flask Meetup
Intro to Jinja2 Templates - San Francisco Flask Meetup
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
 
引き出しとしてのDjango - SoozyCon7
引き出しとしてのDjango - SoozyCon7引き出しとしてのDjango - SoozyCon7
引き出しとしてのDjango - SoozyCon7
 
Bootstrap
BootstrapBootstrap
Bootstrap
 
1cst
1cst1cst
1cst
 
Technical Preview: The New Shopware Admin
Technical Preview: The New Shopware AdminTechnical Preview: The New Shopware Admin
Technical Preview: The New Shopware Admin
 
Flask intro - ROSEdu web workshops
Flask intro - ROSEdu web workshopsFlask intro - ROSEdu web workshops
Flask intro - ROSEdu web workshops
 
Templates81 special document
Templates81 special documentTemplates81 special document
Templates81 special document
 
Templates81 special document
Templates81 special documentTemplates81 special document
Templates81 special document
 
Introduction to Html5
Introduction to Html5Introduction to Html5
Introduction to Html5
 
TURN YOUR CELL PHONE FROM A LIABILITY INTO AN ASSET!
TURN YOUR CELL PHONE FROM A LIABILITY INTO AN ASSET!TURN YOUR CELL PHONE FROM A LIABILITY INTO AN ASSET!
TURN YOUR CELL PHONE FROM A LIABILITY INTO AN ASSET!
 
Fcr 2
Fcr 2Fcr 2
Fcr 2
 
Djangoアプリのデプロイに関するプラクティス / Deploy django application
Djangoアプリのデプロイに関するプラクティス / Deploy django applicationDjangoアプリのデプロイに関するプラクティス / Deploy django application
Djangoアプリのデプロイに関するプラクティス / Deploy django application
 
Xxx
XxxXxx
Xxx
 
Vue.js - zastosowanie i budowa komponentów
Vue.js - zastosowanie i budowa komponentówVue.js - zastosowanie i budowa komponentów
Vue.js - zastosowanie i budowa komponentów
 
Learning django step 1
Learning django step 1Learning django step 1
Learning django step 1
 
HTML5 New and Improved
HTML5   New and ImprovedHTML5   New and Improved
HTML5 New and Improved
 
Django crush course
Django crush course Django crush course
Django crush course
 
Vaadin Components @ Angular U
Vaadin Components @ Angular UVaadin Components @ Angular U
Vaadin Components @ Angular U
 
Private slideshow
Private slideshowPrivate slideshow
Private slideshow
 

Recently uploaded

Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Intelisync
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 

Recently uploaded (20)

Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 

Flask Templates, Inheritance, Forms, Admin

  • 1. Flask Templates (aka Jinja2) by @alanhamlett
  • 2. Blocks ( templates/common/base.html ) Blocks name parts of your template, and can be re-used in child templates. <html> <title>{% block title %}My Website{% endblock %}</title> <body> {% block body %} {% endblock %} </body> </html>
  • 3. Inheritance ( templates/login.html ) {% extends "common/base.html" %} {% block title %}super() - Login{% endblock %} {% block body %} <form method="POST"> <p><input type="text" name="username" /></p> <p><input type="password" name="password" /></p> <p><button type="submit">Login</button></p> </form> {% endblock %}
  • 4. Variable Scope ( templates/common/base.html ) <html> <title>{% block title %}My Website{% endblock %}</title> <body> {% with %} {% set variable = "value" %} {% block body %} {% endblock %} {% endwith %} </body> </html>
  • 5. Variable Scope ( templates/login.html ) {% extends "common/base.html" %} {% block title %}super() - Login{% endblock %} {% block body %} <form method="POST"> <p><input type="hidden" name="variable" value="{{variable}}" /></p> <p><input type="text" name="username" /></p> <p><input type="password" name="password" /></p> <p><button type="submit">Login</button></p> </form> {% endblock %}
  • 6. Rendering Templates ( __init__.py ) from flask import Flask app = Flask(__name__) from flask import render_template @app.route("/login") def login(): return render_template('login.html') if __name__ == "__main__": app.run()
  • 7. Rendering Templates ( __init__.py ) from flask import Flask app = Flask(__name__) from . import views if __name__ == "__main__": app.run()
  • 8. Rendering Templates ( views.py ) from . import app from flask import render_template @app.route("/login") def login(): context = { 'features': [ {'icon': 'free.png', 'name': 'Free'}, {'icon': 'easy.png', 'name': 'Easy'}, {'icon': 'powerful.png', 'name': 'Powerful'}, ], } return render_template('login.html', **context)
  • 9. Rendering Variables ( templates/login.html ) {% extends "common/base.html" %} {% block title %}super() - Login{% endblock %} {% block body %} <h1>Included Features:</h1> <ul> {% for feature in features %} <li><img src="{{STATIC_URL}}img/icons/{{feature.icon}}" /> {{feature.name}}</li> {% endfor %} </ul> <form method="POST"> <p><input type="text" name="username" /></p> <p><input type="password" name="password" /></p> <p><button type="submit">Login</button></p> </form> {% endblock %}
  • 10.
  • 11. Filters ( templates/login.html ) {% extends "common/base.html" %} {% block title %}super() - Login{% endblock %} {% block body %} <h1>Included Features:</h1> <ul> {% for feature in features %} <li><img src="{{STATIC_URL}}img/icons/{{feature.icon}}" /> {{feature.name|lower}}</li> {% endfor %} </ul> <form method="POST"> <p><input type="text" name="username" /></p> <p><input type="password" name="password" /></p> <p><button type="submit">Login</button></p> </form> {% endblock %}
  • 12. Flask-WTF ( forms.py ) from flask.ext.wtf import Form from wtforms import StringField, PasswordField from wtforms.validators import DataRequired, Email, Length class LoginForm(Form): username = StringField('name', validators=[DataRequired(), Email()]) username = PasswordField('name', validators=[DataRequired(), Length(min=6)])
  • 13. Flask-WTF ( views.py ) from . import app from .forms import LoginForm from flask import render_template, request @app.route("/login", methods=('GET', 'POST')) def login(): form = LoginForm(request.form) if request.method == 'POST' and form.validate(): return redirect('/myprofile') return render_template('login.html', form=form)
  • 14. Flask-WTF ( templates/login.html ) {% extends "common/base.html" %} {% block title %}super() - Login{% endblock %} {% block body %} <form method="POST"> <p>Username <input type="text" name="username" value="{{form.data.username or ''}}" /></p> <p>Password <input type="password" name="password" value="{{form.data.password or ''}}" /></p> <p><button type="submit">Login</button></p> </form> {% endblock %}
  • 15. Flask-WTF ( templates/login.html ) ... {% block body %} <form method ="POST" > {% for field in form._fields.values() %} < div class="form-group" > {{ field.label(class="col-sm-3 control-label") }} < div class="col-sm-6 col-md-4" > {{ field(class="form-control") }} {% for error in field.errors %} < p>{{error}}</ p> {% endfor %} </ div> </ div> {% endfor %} < div class="form-group" > < div class="col-sm-6 col-md-4 col-sm-offset-3" > < button type="submit" >Login</ button > </ div> </ div> </ form> {% endblock %} ...
  • 17. Flask-Admin ( admin.py ) from . import app from .models import db, User from flask.ext.admin import Admin from flask.ext.admin.contrib.sqla import ModelView admin = Admin(app) admin.add_view(ModelView(User, db.session))
  • 18. Flask-Admin ( __init__.py ) from flask import Flask app = Flask(__name__) from . import views from . import admin if __name__ == "__main__": app.run()
  • 19. Flask-Admin Extend these Flask-Admin classes to protect your Admin pages: ● flask.ext.admin.AdminIndexView ● sqla.ModelView
  • 20. Flask-Admin ( admin.py ) from . import app from .models import db, User from flask.ext.admin import Admin, AdminIndexView as UnsafeAdminIndexView, expose from flask.ext.admin.contrib.sqla import ModelView class AdminIndexView(UnsafeAdminIndexView): @expose('/') def index(self): if not app.current_user.is_authenticated(): return redirect('/login') if not app.current_user.is_admin: abort(403) return super(AdminIndexView, self).index() @expose('/login/') def login_view(self): return redirect('/login') @expose('/logout/') def logout_view(self): return redirect('/logout') admin = Admin(app, index_view=AdminIndexView(), template_mode='bootstrap3', base_template='admin/custom_base.html') admin.add_view(ModelView(User, db.session))
  • 21. Flask-Admin ( admin.py ) ... class ModelView(sqla.ModelView): edit_template = 'admin/model/edit.html' create_template = 'admin/model/create.html' list_template = 'admin/model/custom_list.html' def __init__(self, *args, **kwargs): if 'exclude' in kwargs: self.form_excluded_columns = kwargs['exclude'] del kwargs['exclude'] if 'show' in kwargs: self.column_list = kwargs['show'] del kwargs['show'] pass_through = [ 'can_create', 'can_edit', 'can_delete', ] for item in pass_through: if item in kwargs: setattr(self, item, kwargs[item]) del kwargs[item] super(ModelView, self).__init__(*args, **kwargs) def is_accessible(self): return app.current_user.is_authenticated() and app.current_user.is_admin admin.add_view(ModelView(User, db.session, category='Users', exclude=['password', 'heartbeats'], can_delete=False)) ...
  • 22. Now go build something cool! Alan Hamlett @alanhamlett on Twitter & GitHub alan@wakatime.com View this online at http://slidesha.re/1wfDzrv