Djangoでフォームを自作する際に、
AuthenticationFormではなく通常のForm(django.forms.Form)を使ってパスワード
を実装したい時に
マスク(パスワードを入れるときに****みたいになるやつ)する方法。
マスクする(widget=forms.PasswordInput())
以下のように、widget=forms.PasswordInput()を指定するだけ。
- forms.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django import forms | |
class MyForm(forms.Form): | |
username = forms.CharField(label='ユーザー名') | |
password = forms.CharField(label='パスワード', widget=forms.PasswordInput(), min_length=8) |
これだけで、パスワード用の汎用的な機能が提供されます。 (ブラウザバックとかリロードした時に、このフィールドだけ消してくれたりもするみたい。)
以下、公式のドキュメントの情報。
PasswordInput¶
class PasswordInput¶
input_type: 'password'
template_name: 'django/forms/widgets/password.html'
Renders as: <input type="password" ...>
Takes one optional argument:
render_value¶
Determines whether the widget will have a value filled in when the form is re-displayed after a validation error (default is False).
要は、レンダリングする時に\<input type="password">で出してくれるよってことですね。
めちゃ便利!!