为了账号安全,请及时绑定邮箱和手机立即绑定

内置视图登录:错误处理和良好实践

内置视图登录:错误处理和良好实践

qq_花开花谢_0 2021-03-31 09:27:26
我想使用Django的内置登录视图: django.contrib.auth.views.login这种观点做得很好。它检测何时登录错误,以及何时尚未验证帐户但错误消息非常短。对于未激活的帐户:这个账号未激活。您知道更冗长的正确方法吗?我喜欢这样的东西:这个账号未激活。已向您发送一封带有激活链接的电子邮件。实际上,我自己登录,并将错误上下文传递给模板:context = {}  if request.method == 'POST':    email = request.POST['email']    password = request.POST['password']    user = authenticate(username=email, password=password)    if user is not None:      if user.is_active:        login_django(request, user)        return redirect('consumer.views.dashboard')      else:        context = {'error': 'disable_account'}    else:      context = {'error': 'invalid_account'}  return render(request, 'login.html', context)在模板中,我可以检查它是哪种错误。
查看完整描述

1 回答

?
湖上湖

TA贡献2003条经验 获得超2个赞

您报告的行为实际上不是由于造成的django.contrib.auth.views.login,而是由于它使用的形式。


在django.contrib.auth.forms.AuthenticationForm:


error_messages = {

    'invalid_login': _("Please enter a correct %(username)s and password. "

                       "Note that both fields may be case-sensitive."),

    'inactive': _("This account is inactive."),

}

我认为您有两种选择:


您可以将表单子类化django.contrib.auth.forms.AuthenticationForm,更改error_messages,并将新表单作为参数传递给登录视图authentication_form。


如果您使用translation,则可以翻译字符串“此帐户无效”。到您想要的字符串。


在我看来,第一种选择是最佳实践,因为不应使用翻译来更改邮件的内容。


查看完整回答
反对 回复 2021-04-06
  • 1 回答
  • 0 关注
  • 177 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号