问题描述
我想创建一个身份验证后端,允许用户只使用他们的电子邮件(无用户名,无密码)log_in。
这是我尝试的。 / p>
backends.py:
从django.conf导入设置
from django.contrib.auth.models import User
class EmailAuthBackend(object):
def authenticate(self,username = None,password = None):
try:
user = User.objects.get(email = username)
如果用户:
返回用户
除了User.DoesNotExist:
返回无
settings.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 =textname =emailvalue =/>
< button type =submit> Valider< / button>
< / form>
查看:
code> def test(request):
email =''
if'email'in request.POST:
email = request.POST.get('email')
如果不是User.objects.filter(email = email):
User.objects.create(email = email)
user = authenticate(username = email)
如果用户不是没有:
如果user.is_active:
auth_login(请求,用户)
返回HttpResponseRedirect(reverse('home'))
它不起作用,用户未通过身份验证。当我去/ admin:$ /
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ EmailAuthBackend'对象没有属性'get_user'
有什么想法可以如何实现? >
对于Django中的每个自定义后端,您需要指定 get_user
函数。请参阅。 get_user
实现可以简单地使用现有的用户表,就像:
def get_user(self,user_id):
try:
return User.objects.get(pk = user_id)
除了User.DoesNotExist:
return None
需要的原因是您需要通过其主源从不同的来源获取用户的情况。
I would like to create an authentification backend that allows users to log_in only using their email (no username, no password).
Here is what I tried.
backends.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
settings.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>
view:
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'))
It doesn't work, the user is not authenticated. And I also have this error when I go to the /admin:
AttributeError at /admin/logout/
'EmailAuthBackend' object has no attribute 'get_user'
Any idea on how I could accomplish that?
For each custom backend in Django, you need to specify the get_user
function. See the documentation. The get_user
implementation can simply use the existing User table, like you are:
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
The reason this is required is for situations where you'd need to fetch the User via its primary key from a different source.
这篇关于定制身份验证后端Django的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!