默认情况下django.contrib.auth.urls
将从此模式创建一个登录页面
(r'^login/$', 'django.contrib.auth.views.login'),
您需要避免/覆盖此 url,然后创建一个新视图来处理新类型的登录。
例如
在 urls.py 中创建一个新的登录 url
(r'^emaillogin/$', 'email_login_view'),
在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.
参考:https ://docs.djangoproject.com/en/1.4/topics/auth/#django.contrib.auth.login