2018-01-02T17:20:33Z

The Flask Mega-Tutorial Part V: User Logins

This is the fifth installment of the Flask Mega-Tutorial series, in which I'm going to tell you how to create a user login subsystem.

For your reference, below is a list of the articles in this series.

In Chapter 3 you learned how to create the user login form, and in Chapter 4 you learned how to work with a database. This chapter will teach you how to combine the topics from those two chapters to create a simple user login system.

The GitHub links for this chapter are: Browse, Zip, Diff.

Password Hashing

In Chapter 4 the user model was given a password_hash field, that so far is unused. The purpose of this field is to hold a hash of the user password, which will be used to verify the password entered by the user during the log in process. Password hashing is a complicated topic that should be left to security experts, but there are several easy to use libraries that implement all that logic in a way that is simple to be invoked from an application.

One of the packages that implement password hashing is Werkzeug, which you may have seen referenced in the output of pip when you install Flask, since it is one of its core dependencies. Since it is a dependency, Werkzeug is already installed in your virtual environment. The following Python shell session demonstrates how to hash a password:

>>> from werkzeug.security import generate_password_hash
>>> hash = generate_password_hash('foobar')
>>> hash
'pbkdf2:sha256:50000$vT9fkZM8$04dfa35c6476acf7e788a1b5b3c35e217c78dc04539d295f011f01f18cd2'

In this example, the password foobar is transformed into a long encoded string through a series of cryptographic operations that have no known reverse operation, which means that a person that obtains the hashed password will be unable to use it to obtain the original password. As an additional measure, if you hash the same password multiple times, you will get different results, so this makes it impossible to identify if two users have the same password by looking at their hashes.

The verification process is done with a second function from Werkzeug, as follows:

>>> from werkzeug.security import check_password_hash
>>> check_password_hash(hash, 'foobar')
True
>>> check_password_hash(hash, 'barfoo')
False

The verification function takes a password hash that was previously generated, and a password entered by the user at the time of log in. The function returns True if the password provided by the user matches the hash, or False otherwise.

The whole password hashing logic can be implemented as two new methods in the user model:

app/models.py: Password hashing and verification

from werkzeug.security import generate_password_hash, check_password_hash

# ...

class User(db.Model):
    # ...

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

With these two methods in place, a user object is now able to do secure password verification, without the need to ever store original passwords. Here is an example usage of these new methods:

>>> u = User(username='susan', email='susan@example.com')
>>> u.set_password('mypassword')
>>> u.check_password('anotherpassword')
False
>>> u.check_password('mypassword')
True

Introduction to Flask-Login

In this chapter I'm going to introduce you to a very popular Flask extension called Flask-Login. This extension manages the user logged-in state, so that for example users can log in to the application and then navigate to different pages while the application "remembers" that the user is logged in. It also provides the "remember me" functionality that allows users to remain logged in even after closing the browser window. To be ready for this chapter, you can start by installing Flask-Login in your virtual environment:

(venv) $ pip install flask-login

As with other extensions, Flask-Login needs to be created and initialized right after the application instance in app/__init__.py. This is how this extension is initialized:

app/__init__.py: Flask-Login initialization

# ...
from flask_login import LoginManager

app = Flask(__name__)
# ...
login = LoginManager(app)

# ...

Preparing The User Model for Flask-Login

The Flask-Login extension works with the application's user model, and expects certain properties and methods to be implemented in it. This approach is nice, because as long as these required items are added to the model, Flask-Login does not have any other requirements, so for example, it can work with user models that are based on any database system.

The four required items are listed below:

  • is_authenticated: a property that is True if the user has valid credentials or False otherwise.
  • is_active: a property that is True if the user's account is active or False otherwise.
  • is_anonymous: a property that is False for regular users, and True for a special, anonymous user.
  • get_id(): a method that returns a unique identifier for the user as a string (unicode, if using Python 2).

I can implement these four easily, but since the implementations are fairly generic, Flask-Login provides a mixin class called UserMixin that includes generic implementations that are appropriate for most user model classes. Here is how the mixin class is added to the model:

app/models.py: Flask-Login user mixin class

# ...
from flask_login import UserMixin

class User(UserMixin, db.Model):
    # ...

User Loader Function

Flask-Login keeps track of the logged in user by storing its unique identifier in Flask's user session, a storage space assigned to each user who connects to the application. Each time the logged-in user navigates to a new page, Flask-Login retrieves the ID of the user from the session, and then loads that user into memory.

Because Flask-Login knows nothing about databases, it needs the application's help in loading a user. For that reason, the extension expects that the application will configure a user loader function, that can be called to load a user given the ID. This function can be added in the app/models.py module:

app/models.py: Flask-Login user loader function

from app import login
# ...

@login.user_loader
def load_user(id):
    return User.query.get(int(id))

The user loader is registered with Flask-Login with the @login.user_loader decorator. The id that Flask-Login passes to the function as an argument is going to be a string, so databases that use numeric IDs need to convert the string to integer as you see above.

Logging Users In

Let's revisit the login view function, which as you recall, implemented a fake login that just issued a flash() message. Now that the application has access to a user database and knows how to generate and verify password hashes, this view function can be completed.

app/routes.py: Login view function logic

# ...
from flask_login import current_user, login_user
from app.models import User

# ...

@app.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is None or not user.check_password(form.password.data):
            flash('Invalid username or password')
            return redirect(url_for('login'))
        login_user(user, remember=form.remember_me.data)
        return redirect(url_for('index'))
    return render_template('login.html', title='Sign In', form=form)

The top two lines in the login() function deal with a weird situation. Imagine you have a user that is logged in, and the user navigates to the /login URL of your application. Clearly that is a mistake, so I want to not allow that. The current_user variable comes from Flask-Login and can be used at any time during the handling to obtain the user object that represents the client of the request. The value of this variable can be a user object from the database (which Flask-Login reads through the user loader callback I provided above), or a special anonymous user object if the user did not log in yet. Remember those properties that Flask-Login required in the user object? One of those was is_authenticated, which comes in handy to check if the user is logged in or not. When the user is already logged in, I just redirect to the index page.

In place of the flash() call that I used earlier, now I can log the user in for real. The first step is to load the user from the database. The username came with the form submission, so I can query the database with that to find the user. For this purpose I'm using the filter_by() method of the SQLAlchemy query object. The result of filter_by() is a query that only includes the objects that have a matching username. Since I know there is only going to be one or zero results, I complete the query by calling first(), which will return the user object if it exists, or None if it does not. In Chapter 4 you have seen that when you call the all() method in a query, the query executes and you get a list of all the results that match that query. The first() method is another commonly used way to execute a query, when you only need to have one result.

If I got a match for the username that was provided, I can next check if the password that also came with the form is valid. This is done by invoking the check_password() method I defined above. This will take the password hash stored with the user and determine if the password entered in the form matches the hash or not. So now I have two possible error conditions: the username can be invalid, or the password can be incorrect for the user. In either of those cases, I flash an message, and redirect back to the login prompt so that the user can try again.

If the username and password are both correct, then I call the login_user() function, which comes from Flask-Login. This function will register the user as logged in, so that means that any future pages the user navigates to will have the current_user variable set to that user.

To complete the login process, I just redirect the newly logged-in user to the index page.

Logging Users Out

I know I will also need to offer users the option to log out of the application. This can be done with Flask-Login's logout_user() function. Here is the logout view function:

app/routes.py: Logout view function

# ...
from flask_login import logout_user

# ...

@app.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('index'))

To expose this link to users, I can make the Login link in the navigation bar automatically switch to a Logout link after the user logs in. This can be done with a conditional in the base.html template:

app/templates/base.html: Conditional login and logout links

    <div>
        Microblog:
        <a href="{{ url_for('index') }}">Home</a>
        {% if current_user.is_anonymous %}
        <a href="{{ url_for('login') }}">Login</a>
        {% else %}
        <a href="{{ url_for('logout') }}">Logout</a>
        {% endif %}
    </div>

The is_anonymous property is one of the attributes that Flask-Login adds to user objects through the UserMixin class. The current_user.is_anonymous expression is going to be True only when the user is not logged in.

Requiring Users To Login

Flask-Login provides a very useful feature that forces users to log in before they can view certain pages of the application. If a user who is not logged in tries to view a protected page, Flask-Login will automatically redirect the user to the login form, and only redirect back to the page the user wanted to view after the login process is complete.

For this feature to be implemented, Flask-Login needs to know what is the view function that handles logins. This can be added in app/__init__.py:

# ...
login = LoginManager(app)
login.login_view = 'login'

The 'login' value above is the function (or endpoint) name for the login view. In other words, the name you would use in a url_for() call to get the URL.

The way Flask-Login protects a view function against anonymous users is with a decorator called @login_required. When you add this decorator to a view function below the @app.route decorators from Flask, the function becomes protected and will not allow access to users that are not authenticated. Here is how the decorator can be applied to the index view function of the application:

app/routes.py: @login\_required decorator

from flask_login import login_required

@app.route('/')
@app.route('/index')
@login_required
def index():
    # ...

What remains is to implement the redirect back from the successful login to the page the user wanted to access. When a user that is not logged in accesses a view function protected with the @login_required decorator, the decorator is going to redirect to the login page, but it is going to include some extra information in this redirect so that the application can then return to the first page. If the user navigates to /index, for example, the @login_required decorator will intercept the request and respond with a redirect to /login, but it will add a query string argument to this URL, making the complete redirect URL /login?next=/index. The next query string argument is set to the original URL, so the application can use that to redirect back after login.

Here is a snippet of code that shows how to read and process the next query string argument:

app/routes.py: Redirect to "next" page

from flask import request
from werkzeug.urls import url_parse

@app.route('/login', methods=['GET', 'POST'])
def login():
    # ...
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is None or not user.check_password(form.password.data):
            flash('Invalid username or password')
            return redirect(url_for('login'))
        login_user(user, remember=form.remember_me.data)
        next_page = request.args.get('next')
        if not next_page or url_parse(next_page).netloc != '':
            next_page = url_for('index')
        return redirect(next_page)
    # ...

Right after the user is logged in by calling Flask-Login's login_user() function, the value of the next query string argument is obtained. Flask provides a request variable that contains all the information that the client sent with the request. In particular, the request.args attribute exposes the contents of the query string in a friendly dictionary format. There are actually three possible cases that need to be considered to determine where to redirect after a successful login:

  • If the login URL does not have a next argument, then the user is redirected to the index page.
  • If the login URL includes a next argument that is set to a relative path (or in other words, a URL without the domain portion), then the user is redirected to that URL.
  • If the login URL includes a next argument that is set to a full URL that includes a domain name, then the user is redirected to the index page.

The first and second cases are self-explanatory. The third case is in place to make the application more secure. An attacker could insert a URL to a malicious site in the next argument, so the application only redirects when the URL is relative, which ensures that the redirect stays within the same site as the application. To determine if the URL is relative or absolute, I parse it with Werkzeug's url_parse() function and then check if the netloc component is set or not.

Showing The Logged In User in Templates

Do you recall that way back in Chapter 2 I created a fake user to help me design the home page of the application before the user subsystem was in place? Well, the application has real users now, so I can now remove the fake user and start working with real users. Instead of the fake user I can use Flask-Login's current_user in the template:

app/templates/index.html: Pass current user to template

{% extends "base.html" %}

{% block content %}
    <h1>Hi, {{ current_user.username }}!</h1>
    {% for post in posts %}
    <div><p>{{ post.author.username }} says: <b>{{ post.body }}</b></p></div>
    {% endfor %}
{% endblock %}

And I can remove the user template argument in the view function:

app/routes.py: Do not pass user to template anymore

@app.route('/')
@app.route('/index')
@login_required
def index():
    # ...
    return render_template("index.html", title='Home Page', posts=posts)

This is a good time to test how the login and logout functionality works. Since there is still no user registration, the only way to add a user to the database is to do it via the Python shell, so run flask shell and enter the following commands to register a user:

>>> u = User(username='susan', email='susan@example.com')
>>> u.set_password('cat')
>>> db.session.add(u)
>>> db.session.commit()

If you start the application and go to the application's / or /index URLs, you will be immediately redirected to the login page, and after you log in using the credentials of the user that you added to your database, you will be returned to the original page, in which you will see a personalized greeting.

User Registration

The last piece of functionality that I'm going to build in this chapter is a registration form, so that users can register themselves through a web form. Let's begin by creating the web form class in app/forms.py:

app/forms.py: User registration form

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import ValidationError, DataRequired, Email, EqualTo
from app.models import User

# ...

class RegistrationForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    email = StringField('Email', validators=[DataRequired(), Email()])
    password = PasswordField('Password', validators=[DataRequired()])
    password2 = PasswordField(
        'Repeat Password', validators=[DataRequired(), EqualTo('password')])
    submit = SubmitField('Register')

    def validate_username(self, username):
        user = User.query.filter_by(username=username.data).first()
        if user is not None:
            raise ValidationError('Please use a different username.')

    def validate_email(self, email):
        user = User.query.filter_by(email=email.data).first()
        if user is not None:
            raise ValidationError('Please use a different email address.')

There are a couple of interesting things in this new form related to validation. First, for the email field I've added a second validator after DataRequired, called Email. This is another stock validator that comes with WTForms that will ensure that what the user types in this field matches the structure of an email address.

The Email() validator from WTForms requires an external dependency to be installed:

(venv) $ pip install email-validator

Since this is a registration form, it is customary to ask the user to type the password two times to reduce the risk of a typo. For that reason I have password and password2 fields. The second password field uses yet another stock validator called EqualTo, which will make sure that its value is identical to the one for the first password field.

When you add any methods that match the pattern validate_<field_name>, WTForms takes those as custom validators and invokes them in addition to the stock validators. I have added two of those methods to this class for the username and email fields. In this case I want to make sure that the username and email address entered by the user are not already in the database, so these two methods issue database queries expecting there will be no results. In the event a result exists, a validation error is triggered by raising an exception of type ValidationError. The message included as the argument in the exception will be the message that will be displayed next to the field for the user to see.

To display this form on a web page, I need to have an HTML template, which I'm going to store in file app/templates/register.html. This template is constructed similarly to the one for the login form:

app/templates/register.html: Registration template

{% extends "base.html" %}

{% block content %}
    <h1>Register</h1>
    <form action="" method="post">
        {{ form.hidden_tag() }}
        <p>
            {{ form.username.label }}<br>
            {{ form.username(size=32) }}<br>
            {% for error in form.username.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
        </p>
        <p>
            {{ form.email.label }}<br>
            {{ form.email(size=64) }}<br>
            {% for error in form.email.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
        </p>
        <p>
            {{ form.password.label }}<br>
            {{ form.password(size=32) }}<br>
            {% for error in form.password.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
        </p>
        <p>
            {{ form.password2.label }}<br>
            {{ form.password2(size=32) }}<br>
            {% for error in form.password2.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
        </p>
        <p>{{ form.submit() }}</p>
    </form>
{% endblock %}

The login form template needs a link that sends new users to the registration form, right below the form:

app/templates/login.html: Link to registration page

    <p>New User? <a href="{{ url_for('register') }}">Click to Register!</a></p>

And finally, I need to write the view function that is going to handle user registrations in app/routes.py:

app/routes.py: User registration view function

from app import db
from app.forms import RegistrationForm

# ...

@app.route('/register', methods=['GET', 'POST'])
def register():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(username=form.username.data, email=form.email.data)
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        flash('Congratulations, you are now a registered user!')
        return redirect(url_for('login'))
    return render_template('register.html', title='Register', form=form)

And this view function should also be mostly self-explanatory. I first make sure the user that invokes this route is not logged in. The form is handled in the same way as the one for logging in. The logic that is done inside the if validate_on_submit() conditional creates a new user with the username, email and password provided, writes it to the database, and then redirects to the login prompt so that the user can log in.

Registration Form

With these changes, users should be able to create accounts on this application, and log in and out. Make sure you try all the validation features I've added in the registration form to better understand how they work. I am going to revisit the user authentication subsystem in a future chapter to add additional functionality such as to allow the user to reset the password if forgotten. But for now, this is enough to continue building other areas of the application.

578 comments

  • #376 Alberto said 2020-03-24T19:27:16Z

    Hi Miguel,

    First of all, thanks for taking the effort of putting this together. I've been learning a lot with it this far. This is the first post I am submitting because I have a question to share, but in all honesty, I should have submitted a thank you note in all the others.

    I noticed in the templates html files there are references to variables (e.g. current_user.is_anonymous) defined in the routes.py. Would that work if I were to define them in other .py files/components? I guess where I am heading with the question is how does the app manages inter-references across the different components.

    Similarly, what is the rational, for instance, in having this line added to the initi.py file and not somewhere else? "login.login_view = 'login'"

    Thank you for your patience in addressing this likely amateur questions!

  • #377 Miguel Grinberg said 2020-03-24T23:01:15Z

    @Alberto: The current_user variable comes from Flask-Login. This extension registers this variable so that you can use it freely from templates. Flask registers some variables as well, such as request and session. If you want to register your own variables you can do so using a context processor function. See https://flask.palletsprojects.com/en/1.1.x/templating/#context-processors.

    For the login_view setting I don't really have a well thought out answer. You can probably add that line in many places, and it'll work fine in all of them. I put it just after the login variable is created to keep related things together.

  • #378 leedj said 2020-03-29T07:12:07Z

    Hi, Miguel. Thanks for the awesome tutorial. I have a question. Where login same user from two browsers, is the current_user same? If so, how can we handle concurrent issues? If not, how the change in one reflect in the other? Thanks a lot

  • #379 Miguel Grinberg said 2020-03-29T11:15:46Z

    @leedj: What concurrency issues are you worried about? Two browsers logged in with the same user can send requests without any issue. If you make a change in one browser the other will not reflect that update until you refresh or switch to another page, but other than that there should be no issues.

  • #380 leedj said 2020-03-31T07:56:27Z

    When I refresh or switch to another page, will current_user be reloaded from database?

  • #381 Miguel Grinberg said 2020-03-31T09:34:36Z

    @leedj: Yes, the logged in user is recorded in the user session, so it is recalled as the user navigates through different pages of the application.

  • #382 Bharat raj Singh said 2020-04-01T10:09:46Z

    If i want to create many user classes..like i want Two types of user,,first is Student and second is Teacher..then how can we create that?

  • #383 Miguel Grinberg said 2020-04-01T10:20:49Z

    @Bharat: if your users share some common behavior, then create a single users table and add a type column that specifies the type of user. If your users do not share common behavior, then just create two completely separate tables in your database.

  • #384 Venkateswaran S said 2020-04-09T13:16:52Z

    Hey Miguel, I am not able to see any of my Flashed messages at the moment. Is that a problem?

  • #385 Miguel Grinberg said 2020-04-09T17:27:41Z

    @Venkateswaran: did you modify your base template to show these flashed messages? Compare it against my version to see if you've made a mistake.

  • #386 Sakib said 2020-04-10T07:19:01Z

    when I run the program it gives me error:

    ImportError: cannot import name 'login' from 'app' (/home/sakib/Desktop/webserver/app/init.py)

    What should I do?

  • #387 Miguel Grinberg said 2020-04-10T13:32:03Z

    @Sakib: each chapter has download links for fully working code for that chapter. Did you see the links at the top of the chapter? Get the code, compare it against yours and hopefully you'll find the mistake.

  • #388 anya said 2020-04-16T21:34:21Z

    Thank you for your wondefrul approach in explaining things

    I have a question if you may allow...

    If I delete a user from the database while the user is logged in, he can continue using the website.. is there a way to log out the user remotely? it seems log_out does not take an argument so you can't pass a user object

  • #389 Miguel Grinberg said 2020-04-17T13:50:18Z

    @anya: If the user is deleted, then the user_loader function should not be able to find the user, and this should prevent the user from accessing protected pages. Something isn't right on your application, check what happens in the user_loader function after the user has been deleted.

  • #390 Aakirti Agrawal said 2020-04-17T14:13:51Z

    Hello Miguel! This is an excellent tutorial. Thanks alot for sharing this. Here is my question: Once I login as a user, when I logout, the index page appears with the 'logout' button intact. Since, I have logged out, is_anonymous field should be false and 'login' should appear.

  • #391 Miguel Grinberg said 2020-04-17T22:46:16Z

    @Aakirti: I see login as soon as I log out. Are you using my code or your own? Maybe you've made a small mistake?

  • #392 Cannot insert a field ID said 2020-04-19T06:43:49Z

    Thank you for this tutorial Miguel. It is by far one of the best I have read.

    I am using this tutorial to do a project app that takes more user information on registration. One of the fields that I use is gender. But this is pulled from a Gender table so the User class has gender_id. The registration table calls the Gender table and shows all the options but then I cannot get it to write back to the User table with the gender_id.

    As you can see from the error, the value passed for gender_id is 'gender'

    Error: sqlalchemy.exc.InternalError: (pymysql.err.InternalError) (1366, "Incorrect integer value: 'gender' for column memento_db.user.gender_id at row 1") [SQL: 'INSERT INTO user (first_name, last_name, dob, gender_id, email, phone, password_hash, about_me, last_seen) VALUES (%(first_name)s, %(last_name)s, %(dob)s, %(gender_id)s, %(email)s, %(phone)s, %(password_hash)s, %(about_me)s, %(last_seen)s)'] [parameters: {'first_name': 'Test', 'last_name': 'Tester', 'dob': datetime.date(1900, 1, 1), 'gender_id': 'gender', 'email': 'test@example.com', 'phone': 12345678, 'password_hash': 'pbkdf2:sha256:50000$iTnCdl1X$c76676ef0aa035d6fad0d15cb7609fcad8d4db7011fac194714f2183cac4f6ae', 'about_me': None, 'last_seen': datetime.datetime(2020, 4, 19, 6, 42, 31, 993542)}]

    Here is my code for reference. I hope you can help me.

    forms.py class RegistrationForm(FlaskForm): email = StringField('Email', validators=[DataRequired(), Email()]) first_name = StringField('First Name', validators=[DataRequired()]) last_name = StringField('Last Name', validators=[DataRequired()]) phone = IntegerField('Mobile Phone', validators=[DataRequired()]) dob = DateField('Date of Birth') gender = QuerySelectField('Gender', query_factory=Gender.query.all, get_pk=lambda x: x.id, get_label=lambda x: x.name, allow_blank=True) password = PasswordField('Password', validators=[DataRequired()]) password2 = PasswordField('Repeat Password', validators=[DataRequired(), EqualTo('password')]) submit = SubmitField('Register')

    routes.py @app.route('/register', methods=['GET','POST']) def register(): if current_user.is_authenticated: return redirect(url_for('index')) form = RegistrationForm() if form.validate_on_submit(): user = User( email=form.email.data, first_name=form.first_name.data, last_name=form.last_name.data, phone=form.phone.data, dob=form.dob.data, gender_id=form.gender.id, ) user.set_password(form.password.data) db.session.add(user) db.session.commit() flash('You have been successfully registered.') return redirect(url_for('login')) return render_template('register.html', title='Register', form=form)

    models.py class Gender(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50)) users = db.relationship('User', backref='users', lazy=True)

    def __repr__(self): return f'<Gender {self.name}>'

    class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) first_name = db.Column(db.String(120)) last_name = db.Column(db.String(120)) dob = db.Column(db.DateTime) gender_id = db.Column(db.Integer, db.ForeignKey('gender.id')) email = db.Column(db.String(120), index=True, unique=True) phone = db.Column(db.Integer, index=True, unique=True) password_hash = db.Column(db.String(128)) about_me = db.Column(db.String(140)) last_seen = db.Column(db.DateTime, default=datetime.utcnow) created_time = db.Column(db.DateTime, server_default=db.func.utcnow()) updated_time = db.Column(db.DateTime, server_default=db.func.utcnow(), server_onupdate=db.func.utcnow())

    def __repr__(self): return f'<User {self.email}>' def set_password(self, password): self.password_hash = generate_password_hash(password) def check_password(self, password): return check_password_hash(self.password_hash, password) def avatar(self, size): digest = md5(self.email.lower().encode('utf-8')).hexdigest() return f'http://www.gravatar.com/avatar/{digest}?d=identicon&s={size}'
  • #393 Miguel Grinberg said 2020-04-19T11:02:05Z

    @Cannot: you assign form.gender.id to your database. Is that correct? Shouldn't that be form.gender.data?

  • #394 alex said 2020-04-22T12:21:30Z

    Hi @Miguel, I tried form.gender.data but get a 'translate' error: AttributeError: 'Gender' object has no attribute 'translate'

    From the reading that I've been doing the translate attribute is a String attribute, but I am not sure why it's not inserting the ID.

  • #395 Miguel Grinberg said 2020-04-22T14:20:38Z

    @alex: it's very hard to follow what you are doing with partial information. I have no idea what this "translate" attribute is for. Is that something you are doing in your application?

  • #396 alex said 2020-04-23T12:27:25Z

    @Miguel, sorry about my explanations. I did the microblog app and it worked perfectly so I tried expanding it. As you can see, I'm a real amateur at this.

    The 'tranlsate' attribute isn't mine, it is an existing attribute. The issue that I am having is that I use QuerySelectField to create the list in the form, and this works fine. However, when the form is submitted form.gender.data returns whatever the repr function returns instead of returning the ID.

    From the documentation (link below), I gather that the QuerySelectField should normally auto-detect the ID and return it but you can specify both the PK and the Label which I did as when I don't it does not know what the label is. Documentation: http://wtforms.simplecodes.com/docs/0.6/ext.html#wtforms.ext.sqlalchemy.fields.QuerySelectField

    I don't understand what I am doing wrong because in my view QuerySelectField should just be returning the ID as per this section of the documentation: "This field only works for queries on models whose primary key column(s) have a consistent string representation. This means it mostly only works for those composed of string, unicode, and integer types. For the most part, the primary keys will be auto-detected from the model, alternately pass a one-argument callable to get_pk which can return a unique comparable key."

    I appreciate your help Miguel, thank you for doing this amazing tutorial.

  • #397 Miguel Grinberg said 2020-04-24T14:38:28Z

    @Alex: you are reading documentation that is very old (v0.6, when current version is 2.3). Regardless, my suggestion is that you follow the source code (https://github.com/wtforms/wtforms-sqlalchemy/blob/master/wtforms_sqlalchemy/fields.py#L26) to figure out why the class cannot figure out the primary key of your objects properly.

  • #398 Joshua Bryant said 2020-05-02T19:14:33Z

    Hey Miguel thanks for the course. I've tested the registration form validations. All work except the email..when I try an already registered email, I get sqalchemy.exc.IntegrityError:(sqlite3.IntetrityError) UNIQUE constraint failed: user.email

  • #399 Miguel Grinberg said 2020-05-02T21:48:29Z

    @Joshua: you are adding an email that already exists in your database. That is not allowed because the email column has a unique constraint.

  • #400 Patrick J. Hess said 2020-05-06T19:30:42Z

    Excellent introduction....In the distance past, I wrote Fortran code on Ibm mainframes. Just now setting up a python web server for an app. An excellent tutorial and I will buy the ebook.

Leave a Comment