Registration View
[app.py]
from flask import Flask, g, render_template, redirect, url_for, flash from flask_login import LoginManager import forms import models DEBUG = True PORT = 8000 HOST = '0.0.0.0' app = Flask(__name__) app.secret_key = 'jnkla@sdioa!sdjoo^paud&1293*hoads.ln10' login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'login' @login_manager.user_loader def load_user(userID): try: models.User.get(models.User.id == userID) except models.DoesNotExist: return None @app.before_request def before_request(): """Connect to the database before each request""" g.db = models.DATABASE g.db.connect() @app.after_request def after_request(response): """Close the database connection after each request""" g.db.close() return response @app.route('/register', methods=['POST', 'GET']) def register(): form = forms.RegisterForm() if form.validate_on_submit(): flash("You have been registered successfully!", "success") models.User.create_user( username=form.username.data, email=form.email.data, password=form.password.data, ) return redirect(url_for('index')) return render_template('register.html', form=form) @app.route('/') def index(): return "Hey!" if __name__ == '__main__': models.initialize() try: models.User.create_user( username='basharghadanfar', email='10.tens@gmail.com', password='123456', admin=True) except ValueError: pass app.run(debug=DEBUG, port=PORT, host=HOST)
from flask_login import LoginManager
from flask.ext.login and from flask.ext.bcrypt have been deprecated!
import forms
So we can import all the available forms into our views. For now, the needed form fields for our register() view.
form = forms.RegisterForm()
Create instance of the registration form and its fields, so the view can display and process its data.
methods=[‘POST’, ‘GET’] GET the view to display form elements, POST to the view to process form data.
form.validate_on_submit()
Returns True if the data submitted into the form are all valid.
“success”
Represents message category.
form.username.data
Data from an individual field.
Registration Form
[register.html]
{% from 'macros.html' import render_field %} <form method="POST" action="" class="form"> {{ form.hidden_tag() }} {% for field in form %} {{ render_field(field) }} {% endfor %} <button type="submit" id="submit">Register!</button> </form>
{% from ‘macros.html’ import render_field %}
Importing the render_field macro into the HTML document
action=””
Redirects back to register.html
{{ form.hidden_tag() }}
Creates a div that has a hidden style attribute, and inside of there is where it puts the hidden tags (e.g. hidden CSRF Token input tag).
render_field(field)
Name of the macro, with the current form field we want to print passed to it.
[macros.html]
{% macro render_field(field) %} <div class="field"> {{ field(placeholder=field.label.text) }} {% if field.errors %} {% for error in field.errors %} <div class="notification error">{{error}}</div> {% endfor %} {% endif %} </div> {% endmacro %}
Macros are like Python functions written in Jinja2 code.
render_field(field)
This macro is named render_field and it takes an argument of field passed to it from an HTML page.
field.label.text
The first argument in each field of the RegisterForm in forms.py is its label. We assign it to the input’s placeholder.
field.errors
Each form field has a list of errors as attribute that takes its values from the field validators.
{{error}}
Printing an errors list item.
Macro Challenge
Create a macro named hide_email. It should take a User as an argument. Print out the email attribute of the User in the following format: t***@example.com for the email test@example.com. This will require splitting the email string and using a for loop.
{% macro hide_email(User): %} {% with name, domain = User.email.split('@') %} {{ name[0] }}{% for letter in name[1:] %}*{% endfor %}@{{ domain }} {% endwith %} {% endmacro %}