我想创建一个身份验证后端,允许用户仅使用他们的电子邮件(无用户名,无密码)登录。
这是我尝试过的。
后端.py:
from django.conf import settings
from django.contrib.auth.models import User
class EmailAuthBackend(object):
def authenticate(self, username=None, password=None):
try:
user = User.objects.get(email=username)
if user:
return user
except User.DoesNotExist:
return None
设置.py:
AUTHENTICATION_BACKENDS = (
'path_to.backends.EmailAuthBackend',
'django.contrib.auth.backends.ModelBackend',
)
html:
<form method="post" action="{% url myproject.views.test %}">
{% csrf_token %}
<input type="text" name="email" value=""/>
<button type="submit">Valider</button>
</form>
看法:
def test(request):
email = ''
if 'email' in request.POST:
email = request.POST.get('email')
if not User.objects.filter(email=email):
User.objects.create(email=email)
user = authenticate(username=email)
if user is not None:
if user.is_active:
auth_login(request, user)
return HttpResponseRedirect(reverse('home'))
它不起作用,用户未通过身份验证。当我转到 /admin 时,我也遇到了这个错误:
AttributeError at /admin/logout/
'EmailAuthBackend' object has no attribute 'get_user'