Django:ユーザーのログインユーザー名の変更/許可も、電子メールを使用できます

StackOverflow https://stackoverflow.com/questions/4267627

質問

私のタイトルが言っているように、ユーザーが自分のユーザー名だけでなく、ユーザーのメールもログインすることを許可する方法があるかどうかを知りたいです。ログイン手順を標準化したいと思います。現時点では、ユーザーに多くの異なる慣習を使用させており、かなり面倒になっています。

役に立ちましたか?

解決

ユニークな電子メールアドレスを実施する場合、おそらくこれを行うことができます。意味のあるユーザーが同じ電子メールアドレスを持つことができないことを意味します。これにより、ユーザーを電子メールアドレスでフェッチしてログインできます。

フォームは次のように見えるかもしれません:

<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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top