1

When I try to register a user, adapting what I learnt from Building a Custom User Model with Extended Fields youtube tutorial, I can't login afterwards despite providing the same password. However I can log in for any I created through the command line. Here is the views.py part that deal with user registration:

views.py

from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth import get_user_model
from django.conf import settings
User = settings.AUTH_USER_MODEL
from django.db import IntegrityError
from django.contrib.auth import login, logout, authenticate
from .forms import TodoForm
from .models import Todo
from django.utils import timezone
from django.contrib.auth.decorators import login_required

def home(request):
    return render(request, 'todo/home.html')

def signupuser(request):
    if request.method == 'GET':
        return render(request, 'todo/signupuser.html', {'form':UserCreationForm()})
    else:
        if request.POST['password1'] == request.POST['password2']:
            try:
                db = get_user_model()
                user = db.objects.create_user(request.POST['email'], request.POST['username'], 
                                            request.POST['firstname'], request.POST['company'], request.POST['mobile_number'], 
                                            password=request.POST['password1'])
                user.save()
                login(request, user)
                print("after login", request, user, request.POST['password1'])
                return redirect('currenttodos')

def loginuser(request):
    if request.method == 'GET':
        return render(request, 'todo/loginuser.html', {'form':AuthenticationForm()})
    else:
        user = authenticate(request, username=request.POST['username'], password=request.POST['password'])
        print("in login: ", request.POST['username'], request.POST['password'])
        if user is None:
            return render(request, 'todo/loginuser.html', {'form':AuthenticationForm(), 'error':'Username and password did not match'})
        else:
            login(request, user)
            return redirect('currenttodos')

The user is still registered but I can't login to my website login page with the password I provided on the sign up page. Even if the user was created.

Example

I tested with: james@gmail.com and the password James.1234. It created the user:

enter image description here

As you can see, a password is registered.

But I was sent back to the login page, where I tried to login again but the password didn't match:

enter image description here

And not to currenttodos. Here are the logs:

after login <WSGIRequest: POST '/signup/'> james@gmail.com James.1234
[21/Jan/2023 20:04:16] "POST /signup/ HTTP/1.1" 302 0
[21/Jan/2023 20:04:16] "GET /current/ HTTP/1.1" 302 0
[21/Jan/2023 20:04:16] "GET /login?next=/current/ HTTP/1.1" 301 0
[21/Jan/2023 20:04:16] "GET /login/?next=/current/ HTTP/1.1" 200 3314
in login:  james@gmail.com James.1234
[21/Jan/2023 20:04:41] "POST /login/?next=/current/ HTTP/1.1" 200 3468

I can't even log in for anybody but the user I created through the command line ... What could be the reason?

Here is my custom user model:

models.py:

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager


class CustomAccountManager(BaseUserManager):

    def create_superuser(self, email, user_name, first_name, password, **other_fields):

        other_fields.setdefault('is_staff', True)
        other_fields.setdefault('is_superuser', True)
        other_fields.setdefault('is_active', True)

        if other_fields.get('is_staff') is not True:
            raise ValueError(
                'Superuser must be assigned to is_staff=True.')
        if other_fields.get('is_superuser') is not True:
            raise ValueError(
                'Superuser must be assigned to is_superuser=True.')

        return self.create_user(email, user_name, first_name, password, **other_fields)

    def create_user(self, email, user_name, first_name,  company, mobile_number, password, **other_fields):

        if not email:
            raise ValueError(('You must provide an email address'))

        email = self.normalize_email(email)
        user = self.model(email=email, user_name=user_name, first_name=first_name, 
                        company=company, mobile_number=mobile_number, password=password, **other_fields)
        user.set_password(password)
        user.save()
        return user

class Newuser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(('email address'), unique=True)
    user_name = models.CharField(max_length=150, unique=True)
    first_name = models.CharField(max_length=150, blank=True)
    mobile_number = models.CharField(max_length=10)
    company = models.CharField(max_length=5)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=False)

    objects = CustomAccountManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['user_name', 'first_name', 'mobile_number']

    def __str__(self):
        return self.user_name

settings.py

AUTH_USER_MODEL = 'todo.NewUser'
Revolucion for Monica
  • 2,848
  • 8
  • 39
  • 78
  • If you mean you cannot login in the admin page, that is probably because of `is_staff = models.BooleanField(default=False)` and `is_active = models.BooleanField(default=False)` – Niko Jan 21 '23 at 19:48
  • In that case you have to [write your own backend](https://docs.djangoproject.com/en/4.1/topics/auth/customizing/#writing-an-authentication-backend). Since Django default backend checks the username credential against the username field. [StackOverflow Example](https://stackoverflow.com/a/37332393/7100120) – Niko Jan 21 '23 at 21:09

0 Answers0