mgP*_*ePe 2 authentication django registration django-registration
我正在尝试创建一个网站,人们只会将他们的电子邮件地址和他们用cookie和所有人登录.在稍后阶段,我会要求他们提供密码和名称,但不会使用用户名.我试图用django-registraition做这个,但我得到错误,我有一些问题.
首先禁用用户名作为登录功能,我把str(time())而不是用户名 - 我正在寻找每次都会改变的东西.
但是,当我跳过身份验证(我目前不需要)时,我收到错误:
'RegistrationProfile' object has no attribute 'backend'
Run Code Online (Sandbox Code Playgroud)
或者,我可以离开身份验证,但后来我不知道如何只通过电子邮件和密码验证它.另外,我不知道如何使下一行工作:
auth.login(request, ProfileUser)
Run Code Online (Sandbox Code Playgroud)
如果有人能让我离开这里,那将是非常棒的.这是一些代码:
我的表格类:
class RegistrationFormCustom(forms.Form):
email = forms.EmailField()
def do_save(self):
new_u = User(username=str(time()),email= self.cleaned_data.get('email'),)
new_u.save()
new_p = Profile.objects.create_profile(new_u)
new_p.save()
return new_p
Run Code Online (Sandbox Code Playgroud)
我的看法:
def registerCustom(request, backend, success_url=None, form_class=None,
disallowed_url='registration_disallowed',
template_name='registration/registration_form.html',
extra_context=None,
initial={}):
form = RegistrationFormCustom(initial=initial)
if request.method == 'POST':
form = RegistrationFormCustom(initial=initial, data=request.POST)
if form.is_valid():
profile = form.do_save()
profile = auth.authenticate(username = profile.user.email, password = form.cleaned_data.get('pass1'))
print(profile)
auth.login(request, profile)
return redirect('/')
else:
pass
return render_jinja(request, 'registration/registration_form.html',
type="register",
form = form
)
Run Code Online (Sandbox Code Playgroud)
我会愉快地张贴任何其他剪辑
您收到'RegistrationProfile' object has no attribute 'backend'错误是因为用户尚未通过身份验证.要记录某人,您必须先调用该authenticate方法,这需要密码.那么,你可以做的是,这是:
from django.contrib.auth import load_backend, login, logout
from django.conf import settings
def _login_user(request, user):
"""
Log in a user without requiring credentials (using ``login`` from
``django.contrib.auth``, first finding a matching backend).
"""
if not hasattr(user, 'backend'):
for backend in settings.AUTHENTICATION_BACKENDS:
if user == load_backend(backend).get_user(user.pk):
user.backend = backend
break
if hasattr(user, 'backend'):
return login(request, user)
Run Code Online (Sandbox Code Playgroud)
然后,要记录某人,只需_login_user使用请求和User模型调用该函数.(这可能是profile.user你的情况),这样做而不是打电话auth.login.我不确定你是如何确定这是否是有效用户,没有密码或用户名,但我会留给你.如果您仍有问题,请告诉我.
简短说明:
这里基本上发生的是Django要求用户进行身份验证,以便通过该login功能登录.该身份验证通常由authenticate函数完成,该函数需要用户名和密码,并检查提供的密码是否与数据库中的散列版本匹配.如果是,则为User模型添加身份验证后端.
因此,由于您没有密码和用户名,因此您只需编写自己的方法即可将身份验证后端添加到User模型中.这就是我的_login_user功能所做的 - 如果用户已经过身份验证,它只是调用login,否则,它首先将默认后端添加到User模型中,而不检查正确的用户名和密码(如同authenticate).
| 归档时间: |
|
| 查看次数: |
2254 次 |
| 最近记录: |