Answer the question
In order to leave comments, you need to log in
Why doesn't the authorization flag change after logging in?
I implemented registration/authorization on the simplest site. The problem is that after the user has logged in, I cannot replace the "login" link with the "logout" link in the template.
To do this, I use a model attribute that is mixed into it using UserMixin. The attribute itself is called is_anonymous and is used in the template like this:
{% if current_user.is_anonymous %}
<a href="{{ url_for('registration') }}">Регистрация</a>
<a href="{{ url_for('login') }}">Вход</a>
{% else %}
<a href="{{ url_for('logout') }}">Выход</a>
{% endif %}
from app import db, login
import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin, LoginManager
class User(UserMixin, db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(40), unique=True, nullable=False)
password_hash = db.Column(db.String(128), nullable=False)
reg_date_utc = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow())
upd_date_utc = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow())
email = db.Column(db.String(40))
desc = db.Column(db.Text)
is_active = db.Column(db.Boolean, default=False)
@login.user_loader
def load_user(id):
return User.query.get(int(id))
from flask import render_template, request, url_for, redirect, flash
from flask_login import current_user, login_user, logout_user, login_required
from app import app, db
from app.forms import RegistrationForm, LoginForm
from app.models import User
...
.....
@app.route('/login', methods=['GET', 'POST'])
def login():
login_form = LoginForm()
if request.method == 'POST' and login_form.validate_on_submit():
user = User.query.filter_by(email=request.form['email']).first()
if user is None or not user.check_password(request.form['password']):
flash('Неверные авторизационные данные')
return redirect(url_for('login'))
else:
login_user(user)
flash('Вы вошли')
return redirect(url_for('index'))
return render_template('login.html', title='Вход', form=login_form)
from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
login = LoginManager(app)
login.login_view = 'login'
from app import routes, models
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question