python - Django:覆盖 AuthenticationForm 的表单字段是否正确?

标签 python django

我发现使用 Django 的 AuthenticationForm 很方便 但由于我们的客户的用户名有点长,不好记,而且我们的客户量也不多,所以我们想在登录页面使用 select widget。所以我使用下面的代码来实现它。 有效

from django.contrib.auth.forms import AuthenticationForm

class SignInForm(AuthenticationForm):
    username = forms.ModelChoiceField(queryset=User.objects.all())

在views.py中:

def post(self, request):
    form = SignInForm(data=request.POST)
    if form.is_valid():
        login(request, form.get_user())
        return HttpResponseRedirect(reverse('account:signin'))
    return render(request, 'account/sign-in.html', {'form': form})

但是,我在文档中找不到任何类似的用法。所以我不确定这样做是否正确。

不知道是不是和ModelForm类似: https://docs.djangoproject.com/en/1.5/topics/forms/modelforms/#overriding-the-default-field-types-or-widgets

我想知道这里发生了什么。我在 SignInForm 中声明的用户名是否会阻止 AuthenticationForm 生成其用户名(如 ModelForm)?但是 AuthenticationForm 成功地将我声明的用户名视为它应该生成的用户名?

最佳答案

看起来不错。

source of AuthenticationForm定义的用户名密码字段。您的子类照常重写了username 字段。

所有表单字段实际上都是Python描述符协议(protocol)的实现。他们只是那里的普通类(class)成员。

关于python - Django:覆盖 AuthenticationForm 的表单字段是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20015452/

相关文章:

python - 构建 tkinter 应用程序的最佳方式?

python - 从宽到长,但我想使用前缀而不是后缀

python - "admin"子目录触发(无意中)Django 管理页面

django - 使用 Celery 和 Django 配置 Raven,无需 Djcelery

python - Django 条目归档

python - SQLAlchemy:按同一个表的多个关系进行计数和排序

Python 3 更改 for 循环中字典键的值不起作用

python - Django makemessages "struct.error: unpack requires a buffer of 4 bytes"

python - 如何在 django 中创建 Group by 和 order by max(...)

python - Serializer.is_valid() 始终返回 False。 Serializer.errors 为空