问题
I'm attempting to use the AuthenticationForm form with django and finding out that I can't seem to get the form to validate. I widdled it down to a simple test(assuming it's correct) that doesn't seem to work. Can anyone see a problem here?
>>> from django.contrib.auth.forms import AuthenticationForm
>>> POST = { 'username': 'test', 'password': 'me', }
>>> form = AuthenticationForm(POST)
>>> form.is_valid()
False
Is there a real reason it won't validate? Am I using it incorrectly? I've basically modeled it after django's own login view.
回答1:
Try:
form = AuthenticationForm(data=request.POST)
回答2:
After a few hours spent finding "Why the hack there are no validation error?!" I run into this page: http://www.janosgyerik.com/django-authenticationform-gotchas/
AuthenticationForm 's first argument is not data! at all:
def __init__(self, request=None, *args, **kwargs):
So thats why you have to pass req.POST to data or pass something else in the first argument. It was already stated in one of the answers here to use:
AuthenticationForm(data=req.POST)
You can also use one of these:
AuthenticationForm(req,req.POST)
AuthenticationForm(None,req.POST)
回答3:
The code of is_valid function:
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.']}
If you see the code of method clean of 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
"The problem" is that does not exits a user with this username and passowrd
来源:https://stackoverflow.com/questions/8421200/using-authenticationform-in-django