6

私は自分のアプリで組み込みのログインを使用しています。これを処理するカスタムバックエンドやパッケージがあります。しかし、それらの多くは私が探しているものではありません。Django-ユーザー名の代わりに電子メールで組み込みのログインビューを使用するには?

私は登録時にdjango登録を介して電子メールを独自に作成しました。今私が望むのは、ユーザー名の代わりにログインページで電子メールを尋ねることだけです。

しかし、django email as usernameのようなカスタムバックエンドを使用すると、django-registrationで使用するとクラッシュします。

私はすべての認証バックエンドを変更したくありません。私はログインページを変更したいだけです。

残りのサイトでは、私はユーザー名を使用するつもりです。私のカスタム管理ページでp.eを書くと:

welcome {{user}} 

ユーザ名を表示する必要があります。電子メールではありません。

私はこれからの方法を見つける必要があります。ハマった。

ありがとうございました。デフォルトdjango.contrib.auth.urlsことで

答えて

9

あなたは、ログインの新しいタイプを処理するための新しいビューを作成するには、このURLを上書き/避けるために必要がある。このパターン

(r'^login/$', 'django.contrib.auth.views.login'), 

からページ内のログを作成します。

参考

views.py

# get default authenticate backend 
from django.contrib.auth import authenticate, login 
from django.contrib.auth.models import User 

# create a function to resolve email to username 
def get_user(email): 
    try: 
     return User.objects.get(email=email.lower()) 
    except User.DoesNotExist: 
     return None 

# create a view that authenticate user with email 
def email_login_view(request): 
    email = request.POST['email'] 
    password = request.POST['password'] 
    username = get_user(email) 
    user = authenticate(username=username, password=password) 
    if user is not None: 
     if user.is_active: 
      login(request, user) 
      # Redirect to a success page. 
     else: 
      # Return a 'disabled account' error message 
    else: 
     # Return an 'invalid login' error message. 
に電子メールでログインをサポートするためにビューを作成

あなたのurls.pyに

(r'^emaillogin/$', 'email_login_view'), 
を新しいログインURLを作成します。 https://docs.djangoproject.com/en/1.4/topics/auth/#django.contrib.auth.login

+0

ありがとうございます:) – alix

2

上記のアプローチはありませんdjango 1.9でもう動作しません。このように定義、

class EmailLoginForm(AuthenticationForm): 
def clean(self): 
    try: 
     self.cleaned_data["username"] = get_user_model().objects.get(email=self.data["username"]) 
    except ObjectDoesNotExist: 
     self.cleaned_data["username"] = "a_username_that_do_not_exists_anywhere_in_the_site" 
    return super(EmailLoginForm, self).clean() 

次にログインURLを定義する場合:別のアプローチは、としてビューで使用する認証フォームを上書きするかもしれない

url(r'^login/$', django.contrib.auth.views.login, name="login", kwargs={"authentication_form": EmailLoginForm}), 
url(r'^', include('django.contrib.auth.urls')), 

あなたは上記のアプローチについての最もよい事認証プロセスでは何も触れていません。それは本当に「クリーン」な解決策ではありませんが、すばやい回避策です。 auth.urlsを含める前にログインパスを定義すると、基本ログインフォームの代わりに評価されます

関連する問題