我想使用 Django 的内置登录 View :django.contrib.auth.views.login
这个 View 做得很好。它会检测登录何时错误以及帐户何时尚未验证但错误消息非常短。
对于未激活的帐户:
This account is inactive.
你知道更冗长的正确方法吗?
我更喜欢这样的东西:
This account is inactive. An email was sent to you with an activation link.
实际上,我自己登录并向模板传递错误上下文:
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)
在模板中我可以检查它是什么类型的错误。
最佳答案
您报告的行为实际上不是由于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
,并将新表单作为的参数传递给登录 View code>authentication_form
.如果您使用 translation ,您可以翻译字符串“This account is inactive.”。到你想要的字符串。
在我看来,第一种选择是最佳做法,因为不应使用翻译来更改消息的内容。
关于python - 内置查看登录: Error handling and good practice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17336458/