Answer the question
In order to leave comments, you need to log in
Why is the form not being imported?
I had a problem of this kind, there is an initial web application, there is authorization with a database, there is a LoginForm form, but I also want to do registration, so I created another Registation class in the same forms.py file, filled everything in as expected
, at first I cursed to this line of code (on Users):
user = Users.query.filter_by(email=self.email.data).first()
from flask import Flask, render_template, redirect, url_for, flash, request
from flask_script import Manager
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Column, Integer, String, DateTime
from flask_migrate import Migrate, MigrateCommand
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import LoginManager, UserMixin, login_required, login_user, current_user, logout_user
from flask_mail import Mail, Message
from forms import LoginForm, Registration
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///usersinfo.db'
app.config['SECRET_KEY'] = 'a really really really really long secret key'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['MAIL_SERVER'] = 'smtp.googlemail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = '[email protected]'
app.config['MAIL_DEFAULT_SENDER'] = '[email protected]'
app.config['MAIL_PASSWORD'] = 'password'
manager = Manager(app)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)
mail = Mail(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'
@login_manager.user_loader
def load_user(user_id):
return db.session.query(Users).get(user_id)
@app.route('/')
@login_required
def admin():
return render_template('login.html')
@app.route('/login/', methods=['post', 'get'])
def login():
if current_user.is_authenticated:
return redirect(url_for('admin'))
form = LoginForm(request.form)
if form.validate_on_submit():
user = db.session.query(Users).filter(Users.username == form.username.data).first()
if user and user.check_password(form.password.data):
login_user(user, remember=form.remember.data)
return redirect(url_for('admin'))
flash("Invalid username/password", 'error')
return redirect(url_for('login'))
return render_template('login.html', form=form)
@app.route('/registration', methods=['post', 'get'])
def registration():
form = Registration(request.form)
if form.validate_on_submit():
user = Users(email=form.email.data,
username=form.username.data,
password_hash=form.password.data,
)
db.session.add(Users)
db.session.commit()
return redirect(url_for('login'))
return render_template('registration.html', form=form)
@app.route('/logout/')
@login_required
def logout():
logout_user()
flash("You have been logged out.")
return redirect(url_for('login'))
class Users(db.Model, UserMixin):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
username = Column(String(80), unique=True, nullable=False)
email = Column(String(100), unique=True, nullable=False)
password_hash = Column(String(80), nullable=False)
created_on = Column(DateTime(), default=datetime.utcnow)
updated_on = Column(DateTime(), default=datetime.utcnow, onupdate=datetime.utcnow)
def __init__(self, email, username, password_hash):
self.email = email
self.username = username
self.password_hash = password_hash
def __repr__(self):
return "<{}:{}>".format(self.id, self.username)
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)
db.create_all()
db.session.commit()
if __name__ == "__main__":
app.run(port=5001)
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, PasswordField, BooleanField
from wtforms.validators import DataRequired, Email, Length, EqualTo
from start import Users
class LoginForm(FlaskForm):
username = StringField("Username", validators=[DataRequired()])
password = PasswordField("Password", validators=[DataRequired()])
remember = BooleanField("Remember Me")
submit = SubmitField()
class Registration(FlaskForm):
username = StringField("username: ", validators=[DataRequired()])
email = StringField("email: ", validators=[DataRequired(), Length(min=6, max=255)])
password_hash = PasswordField("password: ", validators=[DataRequired(), Length(min=6, max=255)])
submit = SubmitField()
def validate(self):
initial_validation = super(Registration, self).validate()
if not initial_validation:
return False
user = Users.query.filter_by(email=self.email.data).first()
if user:
self.email.errors.append("Email already registered")
return False
return True
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