I'm creating a registration page which contains 3 input fields: name, email, password. In my User model class, I've created a user_role method:
from models.base_model import BaseModel
from flask_login import UserMixin
import peewee as pw
class Users(BaseModel, UserMixin):
name = pw.CharField(max_length=100, unique=True)
email = pw.CharField(max_length=100, unique=True)
password = pw.CharField()
role = pw.CharField(max_length=50)
def __init__(self, name, email, password):
self.name = name
self.email = email
self.password = password
def __repr__(self):
return f"User: {self.name}, {self.email}, {self.role}"
def user_roles(self):
user_email = self.email
self.roles = ["user","admin"]
check_email = ["[email protected]"]
if user_email == check_email:
return self.roles == "admin"
else:
return self.roles == "user"
The check_email is use to check if the email that a user fill in the field is equal to the check_email value. If it does, the role should be assign as 'admin'. In my route file, this is what it look like when saving to the database:
if form.validate_on_submit():
name = form.name.data
email = form.email.data
raw_password = form.password.data
password = generate_password_hash(raw_password, method="sha256", salt_length=20)
role = Users.user_roles(email)
new_user = Users(name=name, email=email, password=password, role=role)
Now when I tried to test out the registration form, this is the error it gave me:
I want to know is there a way to fix this error?
PS: I'm doing this for testing purposes to see if I could assign user role. I would probably add more user roles in the future, so I don't think Flask-Admin could help me
CodePudding user response:
You have your user_roles
method defined as a class method when it can and should probably be a static method. Also you are calling user_roles
with the email string but the try to access self.email
in the method. Just change that and you are good to go.
def get_role(email):
check_email = "[email protected]"
if email == check_email:
return "admin"
else:
return "user"
Edit: Forgot to remove brackets as we don't want an array but just the string.