2

I am new in Flask and I just wanted to create a simple market place with it. There are three type of users [sellers, buyers, admins] in my website. I think each type of users should have it's own registration and login because due to their role different type of information should be provided. On the other hand each user may have multiple role in the website therefore I don't think that it could be possible to create just one table for all users and assign role to them. As a result I think there should be three table for each type of users.

since there is only on user loader for users, how can I achieve my goal.

I am not sure whether it is correct or not, I think I could create a complete user with all required columns and based on the address that the user use to register, add the proper information to the database. and based on the address that user uses to login find the proper role and show a proper view.

smhquery
  • 98
  • 6

1 Answers1

2

You can use one model for all types of User:

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    usertype = db.Column(db.String(120))
    password_hash = db.Column(db.String(128))

User Loader will just have the ID :

@login.user_loader
def load_user(id):
    return User.query.get(int(id))

Make sure during register you should ask user type :

class RegistrationForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    email = StringField('Email', validators=[DataRequired(), Email()])
    usertype = SelectField('User Type', choices = [('sellers', 'sellers'),('buyers', 'buyers')], validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    password2 = PasswordField(
        'Repeat Password', validators=[DataRequired(), EqualTo('password')])
    submit = SubmitField('Register')

And No need to provide User type during Login:

class LoginForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    remember_me = BooleanField('Remember Me')
    submit = SubmitField('Sign In')

And in HTMl files you can code accordingly. Take the example of this piece of code taken from base.html.

    {% if current_user.usertype == 'buyers' %}
      <ul class="nav navbar-nav">
        <li class="dropdown">
          <a class="dropdown-toggle" data-toggle="dropdown" href="#">List
          <span class="caret"></span></a> 
          <ul class="dropdown-menu">
             <li><a href="{{ url_for('buyerslist')}}">List of buyers</a></li>
          </ul>
        </li>
      </ul>
    {% endif %}