python - 内置查看登录: Error handling and good practice

标签 python django

我想使用 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."),
}

我认为你有两个选择:

  1. 您将 django.contrib.auth.forms.AuthenticationForm 子类化,更改 error_messages,并将新表单作为 的参数传递给登录 View code>authentication_form.

  2. 如果您使用 translation ,您可以翻译字符串“This account is inactive.”。到你想要的字符串。

在我看来,第一种选择是最佳做法,因为不应使用翻译来更改消息的内容。

关于python - 内置查看登录: Error handling and good practice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17336458/

相关文章:

python - VIM:使用 python 2.5 和 vim 7.2

python - cython 中的数组数组

django - 为什么 Django 模型字段在遍历关系时会不同步?

django - Django 用户错误 : "AttributeError: ' User' object has no attribute 'get' "

django - 使 Django forms.DateField 显示使用本地日期格式

javascript - Django 使用 mpld3 在 HTML 中渲染 Matplotlib 图表

python - 如何使用FastAPI将视频帧和文本返回到HTML页面?

python - ('Nmap not found' , <类 'nmap.nmap.PortScannerError' >)

python - Python导入txt表格文件中的等值线图

Django:从 Pandas 到 Django Rest Framework 的模型查询集