F
F
ForSureN12019-11-08 10:26:10
Flask
ForSureN1, 2019-11-08 10:26:10

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()

after that I did from start import Users
(imported the Users database from start.py)
after that, the error went away, now I do from forms import LoginForm, Registration in start.py:
and when the application starts, this error occurs:
C:\ Users\user8\PycharmProjects\web>python start.py
Traceback (most recent call last):
File "start.py", line 10, in
from forms import LoginForm
File "C:\Users\user8\PycharmProjects\web\forms. py", line 4, in
from start import Users
File "C:\Users\user8\PycharmProjects\web\start.py", line 10, in
from forms import LoginForm
ImportError: cannot import name 'LoginForm' from 'forms' ( C:\Users\user8\PycharmProjects\web\forms.py)
-----------------------------
If I remove the Registration form, then everything works fine, but as soon as I add another Registration to the import, then mistake, please help.
here is the whole code for clarity:
start.py
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)

forms.py
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

-----------------------------------------
If you do everything as I do, everything imports are met, then it gives the following error
C:\Python37.3\python.exe -m flask run
* Serving Flask app "start.py"
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
Usage: python -m flask run [OPTIONS]
Error: While importing "start", an ImportError was raised:
Traceback (most recent call last):
File "C:\Python37.3\lib\site-packages \flask\cli.py", line 240, in locate_app
__import__(module_name)
File "C:\Users\user8\PycharmProjects\web\start.py", line 10, in
from forms import LoginForm, Registration
File "C:\Users\user8\PycharmProjects\web\forms.py", line 4, in
from start import Users
ImportError: cannot import name 'Users' from 'start' (C:\Users\user8\PycharmProjects\web\start.py)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question