我想使用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)
在模板中我可以检查它是什么类型的错误。
答案 0 :(得分:1)
您报告的行为实际上不是由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,则可以翻译字符串“此帐户处于非活动状态”。到你想要的字符串。
在我看来,第一种选择是最佳做法,因为翻译不应用于更改邮件的内容。