admin.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. from flask_admin import form
  2. from flask_login import current_user
  3. import wtforms.validators
  4. from project import admin, db
  5. from project import User
  6. from library.admin_utils import ProtectedModelView
  7. def validate_password_required_if_confirm(form, field):
  8. """Validates that a password is required if this is a new user."""
  9. if form.password2_confirm.data and not field.data:
  10. raise wtforms.validators.ValidationError('Password is required if \'confirm password\' is given')
  11. class UserView(ProtectedModelView):
  12. column_list = ('email',)
  13. form_excluded_columns = ('password',)
  14. form_args = dict(
  15. email=dict(
  16. validators=[wtforms.validators.InputRequired()],
  17. ))
  18. def scaffold_form(self):
  19. from project import app
  20. form_class = super(UserView, self).scaffold_form()
  21. form_class.password2 = wtforms.PasswordField('New Password', validators=[validate_password_required_if_confirm, wtforms.validators.EqualTo('password2_confirm', message='Passwords must match')])
  22. form_class.password2_confirm = wtforms.PasswordField('Repeat Password')
  23. return form_class
  24. def on_model_change(self, form, model, is_created):
  25. if len(model.password2):
  26. model.set_password(db.session, form.password2.data)
  27. admin.add_view(UserView(User, db.session, name='Users'))