Django : authenticate() is not working for users created by register page, but working for those users who were created by admin
<p>I want to make a register/login API for users. 
Problem is like this : 
If I create user via admin site, login is working properly.</p>

<p>If I create user via register page made by me, login isn't working.(authenticate() function is returning None, even though that user is still in user table.)</p>

<p>I go to admin site, go to the link to change password and give the same password again. After that I can login successfully.</p>

<p>I think problem is either in saving password or login.
I have crossed checked a lot but couldn't figure out.
I am giving all files. You may go through important code.</p>

<p>models.py
    </p>

<pre class="lang-py prettyprint-override"><code>from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
from datetime import datetime

class Recruiter(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    company_name = models.CharField(max_length=120)
    HR_office_number = models.CharField(max_length=15)
    HR_mobile_number = models.CharField(max_length=15)

def __str__(self):
    return self.user.username
</code></pre>

<p>forms.py
    </p>

<pre class="lang-py prettyprint-override"><code>from django import forms
from .models import Recruiter, User
from django.core.exceptions import ValidationError

class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput(), max_length=128)
    confirm_password = forms.CharField(widget=forms.PasswordInput(), max_length=128)
    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'username', 'email']

    def __init__(self, *args, **kwargs):
        super(UserForm, self).__init__(*args, **kwargs)
        self.fields['first_name'].required = True
        self.fields['last_name'].required = True
        self.fields['email'].required = True
        self.fields['username'].help_text = None

    def clean_confirm_password(self):
        password1 = self.cleaned_data.get('password')
        password2 = self.cleaned_data.get('confirm_password')
        if not (password1 and password2):
            raise forms.ValidationError("You must confirm your password")
        elif password1 != password2:
            raise forms.ValidationError("Your passwords do not match")
        return password1


class RecruiterForm(forms.ModelForm):
    class Meta:
        model = Recruiter
        fields = ('company_name', 'HR_mobile_number', 'HR_office_number')
</code></pre>

<p>views.py
    </p>

<pre class="lang-py prettyprint-override"><code>from django.shortcuts import render
from django.contrib.auth.models import User
from .models import Recruiter
from .forms import RecruiterForm, UserForm, RecruiterLoginForm
from django.urls import reverse
from django.http import HttpResponse,HttpResponseRedirect
from django.db import IntegrityError
from django.contrib.auth import authenticate, login, logout

def register(request):
    context = request.POST
    registered = False

    if request.method == 'POST':
        user_form = UserForm(data=request.POST)
        recruiter_form = RecruiterForm(data=request.POST)
        if user_form.is_valid() and recruiter_form.is_valid():
            user = user_form.save()
            try:
                user.set_password(user.password)
                user.save()
            except IntegrityError as e:
                user.delete()
                return HttpResponse(e.message)
            try:
                recruiter = recruiter_form.save(commit=False)
                recruiter.user = user
                recruiter.save()
            except IntegrityError as e:
                recruiter.delete()
                return HttpResponse(e.message)
            registered = True
        else:
            pass
            #print form.errors
    else:
        recruiter_form = RecruiterForm()
        user_form = UserForm()

    return render(request, 'recruiter/register.html', {'user_form':user_form,
                'recruiter_form':recruiter_form, 'registered':registered}, context)



def login_recruiter(request):
    context = request.POST
    if request.user.is_authenticated():
        return HttpResponse("Logged in")
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        print user
        if user:
            if user.is_active:
                login(request, user)
                return HttpResponse("Success")
            else:
                return HttpResponse("Not active")
        else:
            return HttpResponse("Invalid")
    else:
        return render(request, 'recruiter/login_recruiter.html', {}, context)
</code></pre>

<p>register.html
    </p>

<pre class="lang-py prettyprint-override"><code>{% if registered %}
    &lt;h1&gt;Registered&lt;/h1&gt;&lt;br /&gt;
{% else %}
&lt;form id="user_form" method="post" action="{% url 'recruiter:register' %}" enctype="multipart/form-data"&gt;
    {% csrf_token %}
    {{ user_form.as_p}}
    {{ recruiter_form.as_p}}
    &lt;input type="submit" name="submit" value="Register" /&gt;
&lt;/form&gt;
{% endif %}
</code></pre>

<p>login_recruiter.html
    </p>

<pre class="lang-py prettyprint-override"><code>&lt;form id="login_form" method="post" action="{% url 'recruiter:login_recruiter' %}"&gt;
        {% csrf_token %}
        Username: &lt;input type="text" name="username" value="" size="120" /&gt;
        &lt;br /&gt;
        Password: &lt;input type="password" name="password" value="" size="120" /&gt;
        &lt;br /&gt;
        &lt;input type="submit" value="submit" /&gt;
&lt;/form&gt;
</code></pre>

<p>The issue is in how you set the password. You've excluded the password from the list of fields on the model form, so it is not set on save. So doing <code>user.set_password(user.password)</code> is effectively setting the password to the hash of None. Instead, do this:</p>

<pre><code>user = user_form.save(commit=False)
user.set_password(user_form.cleaned_data['password']
user.save()
</code></pre>

<p>Note that even in your original code there was no way setting the password could cause IntegrityError, so that try/except was unnecessary; it's even more so now, so you should remove it.</p>

python django django-views