タイトルにあるように、ユーザーが自分のユーザー名だけでなく、ユーザーの電子メールも使用してログインできるようにする方法があるかどうかを知りたいです。ログイン手順を標準化したいのは、現時点ではユーザーにさまざまな規則を使用させているため、かなり面倒になっているからです。
2 に答える
一意の電子メール アドレスを強制する場合は、おそらくこれを行うことができます。ユーザーが同じ電子メール アドレスを持つことはできないという意味です。このようにして、電子メール アドレスでユーザーを取得し、ログインすることができます。
フォームは次のようになります。
<form method="post" action="{% url myproject.views.login %}">
<p>Username</p>
<input type='text' name='username'/>
<p>Password</p>
<input type='password' name='password'/>
<input type="submit" value="Login"/>
</form>
ビュー メソッドは次のようになります。
def login( request ):
username = request.POST['username']
password = request.POST['password']
user = User.objects.filter( email = username )[0]
if( user is not None ):
# -- the user was retrieved by an email address
# -- now you can authenticate and log them in log them in
from django.contrib import auth
user = auth.authenticate( user.username, password )
if( user is not None ):
auth.login( user, request )
OpenID は別の方法かもしれません: http://bit.ly/a2OlHX
ユーザーごとに固有の電子メール アドレスを確保する: http://bit.ly/aOaAbw
今のところ、問題を「解決」したと思います。少なくとも機能しています。独自の認証バックエンドを使用することにしました。ファイル「auth_backends.py」を作成し、settings.py の AUTHENTICATION_BACKENDS に追加しました。
ログイン フォームのフィールドに「ユーザー名」とパスワードしか含まれていません。入力したユーザー名が実際に彼のユーザー名または電子メールであるかどうかを確認する唯一の方法は、.find('@') を実行することです。それを確認するより良い方法はありますか?これで十分でしょうか?私がこれを行っている全体的な理由は、ユーザーが自分のユーザー名 (実際には数字で構成される「id」) よりも自分の電子メールを覚えやすいからです。
メールの重複にも気をつけなければなりません。
from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from django.core.exceptions import ImproperlyConfigured
from django.db.models import get_model
from django.contrib.auth.models import User
class CustomUserModelBackend(ModelBackend):
def authenticate(self, **credentials):
if 'username' in credentials:
if credentials['username'].find('@') > 0:
return self.authenticate_by_email(**credentials)
else:
return self.authenticate_by_username(**credentials)
def authenticate_by_username(self, username=None, password=None):
try:
user = User.objects.get(username=username)
if user.check_password(password):
return user
except User.DoesNotExist:
return None
def authenticate_by_email(self, username=None, password=None):
try:
user = User.objects.get(email=username)
if user.check_password(password):
return user
except User.DoesNotExist:
return None