2011-12-07 21 views
23

我正在嘗試使用Django的AuthenticationForm表單,並發現我似乎無法獲取表單進行驗證。我把它放在一個簡單的測試(假設它是正確的),似乎並不奏效。任何人都可以在這裏看到問題?在Django中使用AuthenticationForm

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

有沒有一個真正的原因,它不會驗證?我使用不正確?我已經基於django自己的登錄視圖對它進行了建模。

回答

37

嘗試:

form = AuthenticationForm(data=request.POST) 
+0

謝謝。不知道我是如何在django的默認視圖中錯過的。我只是把POST放入實例中,而不使用kwarg。任何想法有什麼不同? –

+3

如果內存服務,AuthenticationForm與其他服務稍有不同。 Django中存在一些不一致的地方。通常我使用以下形式實例化表單:form = MyForm(request.POST或None) – Brandon

2

is_valid函數的代碼:

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 

的代碼「的問題」是不退出的用戶使用該用戶名和passowrd

+0

你在哪裏看到這個is_valid? django.forms.BaseForm?你運行的是什麼版本的django?我在1.3.1這裏。如果這是使用相同的後端作爲django管理員,我已經嘗試了一個有效的用戶/傳遞... –

+0

在後備箱:https://code.djangoproject.com/browser/django/trunk/django/forms/forms。 py#L119或Django 1.3.1 https://code.djangoproject.com/browser/django/tags/releases/1.3.1/django/forms/forms.py#L116 – Goin

+0

告訴我form.errors的值 – Goin

13

經過幾個小時的尋找「爲什麼黑客沒有驗證錯誤?!」我碰到這個頁面:http://www.janosgyerik.com/django-authenticationform-gotchas/

AuthenticationForm的第一個參數是不是數據!在所有:

def __init__(self, request=None, *args, **kwargs): 

所以這就是爲什麼你必須通過req.POST數據或傳遞的第一個參數別的東西。它在其中一個答案已經在這裏說明使用方法:

AuthenticationForm(data=req.POST) 

您也可以使用下列操作之一:

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

良好地調用'data ='。 – freb