I'm learning Flask, and I'm trying out the exploreflask tutorial . My register form is not working. The error is in server.py and says:
password = form.password.data
TypeError: __init__() got an unexpected keyword argument 'password'
I'm using Flask-SQLAlchemy's declarative_base
, so I believe the hybrid_property
on the password should work fine, but that is not the case!
models.py:
from flask.ext.login import UserMixin
from flask.ext.bcrypt import Bcrypt
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy import Column, Integer, String
from database import Base
# Base is using Flask-SqlAlchemy's declarative_base()
class User(Base, UserMixin):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
email = Column(String(120), unique=True)
_password = Column(String(120))
def __init__(self, name=None, email=None):
self.email = email
def __repr__(self):
return '<User %r>' % (self.name)
@hybrid_property
def password(self):
return self._password
@password.setter
def _set_password(self, plaintext):
self._password = bcrypt.generate_password_hash(plaintext)
def verify_password(self, plaintext):
return bcrypt.check_password_hash(self._password, plaintext)
forms.py:
from flask_wtf import Form
from wtforms import StringField, PasswordField
from wtforms.fields.html5 import EmailField
from wtforms.validators import InputRequired
class RegisterForm(Form):
email = EmailField('email', validators=[InputRequired()])
password = PasswordField('password', validators=[InputRequired()])
server.py:
@app.route('/register', methods=["GET", "POST"])
def register():
form = RegisterForm()
if form.validate_on_submit():
user = User(
email = form.email.data,
password = form.password.data
)
db_session.add(user)
db_session.commit()
return redirect(url_for('login.html'))
return render_template('register.html', form=form)
I'm not sure what's wrong?
In server.py you are initializing a User instance with email and password. However, your constructor for User class accepts only arguments name and email.
So you should change your constructor that it accepts password as well.
def __init__(self, name=None, email=None, password=None)
#your constructor logic
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.