在Django中使用AuthenticationForm

Mik*_*ltz 28 django django-forms

我正在尝试使用带有django的AuthenticationForm表单,并发现我似乎无法获得要验证的表单.我把它弄成一个简单的测试(假设它是正确的)似乎不起作用.谁能在这里看到问题?

>>> from django.contrib.auth.forms import AuthenticationForm
>>> POST = { 'username': 'test', 'password': 'me', }
>>> form = AuthenticationForm(POST)
>>> form.is_valid()
False
Run Code Online (Sandbox Code Playgroud)

是否有真正的原因无法验证?我使用不正确吗?我基本上是在django自己的登录视图之后建模的.

Bra*_*don 48

尝试:

form = AuthenticationForm(data=request.POST)
Run Code Online (Sandbox Code Playgroud)

  • 如果内存服务,AuthenticationForm与其他内容略有不同.Django中存在一些不一致的地方.通常我使用:form = MyForm(request.POST或None)实例化表单 (4认同)
  • 谢谢。不知道我是如何在 django 的默认视图中错过的。我的所有其他表单我只是将 POST 扔到实例中,而不使用 kwarg。知道这里有什么不同吗? (2认同)

dar*_*ess 18

花了几个小时找到"为什么黑客没有验证错误?!" 我遇到这个页面:http://www.janosgyerik.com/django-authenticationform-gotchas/

AuthenticationForm的第一个参数不是数据!根本:

def __init__(self, request=None, *args, **kwargs):
Run Code Online (Sandbox Code Playgroud)

这就是为什么你必须将req.POST传递给数据或在第一个参数中传递其他东西.在这里使用的答案中已经说明了:

AuthenticationForm(data=req.POST)
Run Code Online (Sandbox Code Playgroud)

您还可以使用以下方法之一:

AuthenticationForm(req,req.POST)
AuthenticationForm(None,req.POST)
Run Code Online (Sandbox Code Playgroud)