2

我想使用 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)

在模板中我可以检查它是什么类型的错误。

4

1 回答 1

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."),
}

我认为你有两个选择:

  1. 您对表单进行子类化django.contrib.auth.forms.AuthenticationForm、更改error_messages并将新表单作为 的参数传递给登录视图authentication_form

  2. 如果您使用translate,则可以翻译字符串“此帐户处于非活动状态”。到你想要的字符串。

在我看来,第一个选项是最佳实践,因为不应该使用翻译来更改消息的内容。

于 2013-06-27T07:42:31.513 回答