Yax Yax - 2 months ago 15
Python Question

WEIRD Django AuthenticationForm Behaviour

I have, all day, tried to figure this out but I can't really see where the problem is coming from.

I have a Django

AuthenticationForm
that seems to be submitting data somehow but not getting validated.

forms.py:

class LoginForm(AuthenticationForm):
username = forms.CharField(widget=forms.TextInput(attrs={'name': 'username'}))
password = forms.CharField(widget=forms.PasswordInput(attrs={'name': 'password'}))


views.py:

def index(request):
template = 'myapp/login.html'
if request.method == "POST":
print request.POST #prints QueryDict with its data
reg = LoginForm(request.POST or None)
if reg.is_valid():
return HttpResponse('Success: Form is valid!')
else:
return HttpResponse('Error: Form not valid')

loginform = LoginForm()
context = {'loginform':loginform}
return render(request, template, context)


HTML:

<form method="post" action=".">
{% csrf_token %}
<h2>Sign in</h2>
<p class="text-danger">{{loginform.errors}}</p>
{{ loginform.as_p }}
<button name = "signin" type="submit" value="0">Sign in</button>
</form>


The
print request.POST
in my views.py prints QueryDict: {u'username': [u'yax'], u'csrfmiddlewaretoken': [u'r8y1PaVNjxNWypdzP
MaFe1ZL7IkE1O7Hw0yRPQTSipW36z1g7X3vPS5qMMX56byj'], u'password': [u'sdfdsfsddfs']
, u'signin': [u'0']}
but the
reg.is_valid()
keeps returning
false
.

EDIT:

I have also tried printing out
reg.errors
but it doesn't print out anything.

Answer

Try making the following change:

reg = LoginForm(data=request.POST)

AuthenticationForm is slightly different in that it needs the data argument.

Also note that you should test it with actually valid username and password combinations (that correspond to an existing user), since AuthenticationForm checks for that as well.