What's the correct way to render PasswordField? #359
-
Assuming you have a At the moment I have something like this: class UserAdminView(ModelView, model=User):
column_list = ("id", "email", "first_name", "last_name", "subscription_plan")
form_overrides = {
"password": wtforms.fields.PasswordField,
} For creating a new user, this works fine. But when I'm trying to edit an existing user, the current password is not displayed in the password input field (likely because of the I guess what I'm looking for is a way to dynamically change the field type or its arguments, so that for creating a new user we use the stock |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 12 replies
-
@aminalaee Is there any simple solution to have basic user/password functionality? It would be nice if there will be some recipe to have username + hashing password create and edit forms SQLAdmin is pretty nice in its diverse and rich functionality, but the lack of such fundamental features makes it slightly painful to use :) |
Beta Was this translation helpful? Give feedback.
-
This should cover your use-case: #783 |
Beta Was this translation helpful? Give feedback.
-
I also wanted to update the password on the edit page, unlike in #783, so I wrote the following code. class UserAdmin(ModelView, model=User):
async def scaffold_form(self) -> type[Form]:
"""Make hashed_password an optional password field with no initial value."""
form = await super().scaffold_form()
form.hashed_password = wtforms.PasswordField(
"Password", render_kw={"class": "form-control"}
)
return form
async def insert_model(self, request: Request, data: dict) -> Any:
"""Only when creating a new user, hashed_password is required."""
if not data["hashed_password"]:
raise ValidationError("Password is required")
return await super().insert_model(request, data)
async def on_model_change(
self, data: dict[str, Any], model: Any, is_created: bool, request: Request
) -> None:
"""When editing a user, leave the password empty to keep the current one; otherwise, hash it."""
if not is_created:
if not data["hashed_password"]:
data["hashed_password"] = model.hashed_password
return
data["hashed_password"] = await get_password_hash(data["hashed_password"]) # My own custom hashing function |
Beta Was this translation helpful? Give feedback.
This should cover your use-case: #783