Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Django中使用AuthenticationForm_Django_Django Forms - Fatal编程技术网

在Django中使用AuthenticationForm

在Django中使用AuthenticationForm,django,django-forms,Django,Django Forms,我试图将AuthenticationForm表单与django一起使用,但发现我似乎无法使表单进行验证。我把它简化为一个简单的测试(假设它是正确的),似乎不起作用。有人看到这里有问题吗 >>> from django.contrib.auth.forms import AuthenticationForm >>> POST = { 'username': 'test', 'password': 'me', } >>> form = Authe

我试图将AuthenticationForm表单与django一起使用,但发现我似乎无法使表单进行验证。我把它简化为一个简单的测试(假设它是正确的),似乎不起作用。有人看到这里有问题吗

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

有没有真正的理由不能验证它?我用错了吗?我基本上是按照django自己的登录视图来建模的。

的代码是有效的函数:

return self.is_bound and not bool(self.errors)


>>> form.errors
{'__all__': [u'Please enter a correct username and password. Note that both fields are case-sensitive.']}
如果您看到方法代码清除AuthenticationForm

def clean(self):
    username = self.cleaned_data.get('username')
    password = self.cleaned_data.get('password')

    if username and password:
        self.user_cache = authenticate(username=username, password=password)
        if self.user_cache is None:
            raise forms.ValidationError(_("Please enter a correct username and password. Note that both fields are case-sensitive."))
        elif not self.user_cache.is_active:
            raise forms.ValidationError(_("This account is inactive."))
    self.check_for_test_cookie()
    return self.cleaned_data
“问题”是没有使用此用户名和密码退出用户,请尝试:

form = AuthenticationForm(data=request.POST)

在花了几个小时寻找“为什么黑客没有验证错误?!”之后,我进入了这个页面:

AuthenticationForm的第一个参数不是数据!总之:

def __init__(self, request=None, *args, **kwargs):
这就是为什么必须在第一个参数中传递req.POST到数据或传递其他内容。这里的一个答案中已经说明了使用:

AuthenticationForm(data=req.POST)
您还可以使用以下选项之一:

AuthenticationForm(req,req.POST)
AuthenticationForm(None,req.POST)

你在哪里看到这是有效的?django.forms.BaseForm?你在运行什么版本的django?我现在是1.3.1。如果这与django admin使用相同的后端,那么我已尝试在trunk:或django 1.3.1表单中使用有效的user/pass…。errors为空。上面的答案解决了这个问题。就在眼前。谢谢你提供的信息,谢谢。我不知道我怎么会在django的默认视图中忽略了这一点。我的所有其他表单都只是将POST扔到实例中,而不使用kwarg。你知道这里有什么不同吗?如果内存可用,那么AuthenticationForm与其他的稍有不同。在Django,这里和那里有一些不一致之处。通常,我会使用以下命令实例化表单:form=MyForm(request.POST或None)需要是
AuthenticationForm(None,request.POST)
@citynorman Keping Stack Overflow-answers-updated将是一项全职工作。对“data=”的调用很好。