Django Login Form Returning false on is_valid() if username already exists
<p>I have a login form I created from Django's <code>User</code> model:</p>

<p><strong>forms.py</strong>:</p>

<pre><code>class LoginForm(ModelForm):
    class Meta:
        model = User
        fields = ['username', 'password']
        widgets = {
            'username': forms.TextInput(attrs={'placeholder': '@username'}),
            'password': forms.PasswordInput(attrs={'placeholder': 'Password'})
        }
</code></pre>

<p><strong>views.py</strong>:</p>

<pre><code>    reg = LoginForm(request.POST or None)
    if reg.is_valid():
        return HttpResponse('Success: valid form')
    else:
        return HttpResponse('Error: invalid form')
</code></pre>

<p>Now if I try login in with a <em>username</em> that is not registered it returns <strong>Success: valid form</strong> but if it is a 
username that already exists, it says <strong>Error: invalid form</strong>.</p>

<p>I tried doing this in command line and below is what I get (I first tried it with a username that is register, <strong>yax</strong>):</p>

<pre><code>In [2]: data = {'username':'yax', 'password':'wrong_password'}
In [3]: form = LoginForm(data)

In [4]: form.is_valid()
Out[5]: False
In [6]: form.errors
Out[7]: {'username': [u'A user with that username already exists.']}

In [8]: data = {'username':'wrong_name', 'password':'wrong_password'}
In [9]: form = LoginForm(data)

In [10]: form.is_valid()
Out[11]: True
In [12]: form.errors
Out[13]: {}
</code></pre>

<p>Would be glad I can know why I am getting this error and how do I solve it. </p>

<p>A login form should not be a ModelForm. That's for creating or editing model instances - in this case, since you don't supply an <code>instance</code> parameter, Django assumes you want to create a new user.</p>

<p>Just use a standard Form and define the username and password fields explicitly.</p>

<p>Alternatively, use the <a href="https://docs.djangoproject.com/en/1.10/topics/auth/default/#django.contrib.auth.forms.AuthenticationForm" rel="nofollow">AuthenticationForm</a> supplied in django.contrib.auth.forms, wich takes care of the entire authentication/login process for you.</p>

python django forms