Cannot login on my website with a user I create in django admin

48 Views Asked by At

I have a login and signup page, where a user that signs up is able to login and i can view this user in the admin portal as shown in the screenshots below:


Example User created through signup page: Username=usertest Password=pass123

Signup page

Signed up user visible in admin portal (note: password is hashed)


However, when i create a user in admin portal I cannot login with that user in login. This may be due to the password that is being stored as it is not hashed when viewing admin portal-not too sure:


Example User created through django admin portal: Username=usertest2 Password=pass1234

User created via admin portal (note: password is not hashed)

Login says invalid despite user present in admin view


I have tried to have a look and think it might be the password is not hashed when creating a new user in admin portal and so when login is compared this might be causing the issue- not too sure.

Below are my codes, I can share further code that can help solve this too:

models.py

from django.db import models
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    username = models.CharField(max_length=50, unique=True)
    profile_pic = models.ImageField(null=True, blank=True, upload_to="images/profile-images")
    date_of_birth = models.DateField(null=True, blank=True)
    email = models.EmailField()

views.py

from django.http import HttpResponse, HttpRequest, JsonResponse
from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate
from django.contrib import auth
from django.contrib import messages
from .serializers import *
from .models import *
from .forms import *

def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST, request.FILES)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']

            # Check if the user with the given username already exists
            if User.objects.filter(username=username).exists():
                messages.error(request, 'Username is already taken. Please choose a different one.')
            else:
                new_user = User.objects.create(username=username)
                new_user.set_password(password)

                if 'profile_pic' in request.FILES:
                    new_user.profile_pic = request.FILES['profile_pic']

                if 'date_of_birth' in form.cleaned_data:
                    date_of_birth = form.cleaned_data['date_of_birth']
                    new_user.date_of_birth = date_of_birth

                new_user.save()

                user = auth.authenticate(username=username, password=password)

                if user is not None:
                    auth.login(request, user)
                    messages.success(request, 'Registration successful. You are now logged in.')
                    return redirect('home')
        else:
            messages.error(request, 'Error during registration. Please correct the errors below.')
    else:
        form = SignUpForm()

    return render(request, 'api/spa/signup.html', {'form': form})

def user_login(request: HttpRequest) -> HttpResponse:
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']

            user = authenticate(request, username=username, password=password)

            if user is not None:
                login(request, user)
                messages.success(request, 'Login successful.')
                return redirect('home')  # Replace 'home' with the actual name of your home URL
            else:
                messages.error(request, 'Invalid username or password. Please try again.')
        else:
            messages.error(request, 'Error during login. Please correct the errors below.')
    else:
        form = LoginForm()

    return render(request, 'api/spa/login.html', {'form': form})

admins.py

from django.contrib import admin
from .models import User, Article, Category

# Register your models here.

admin.site.register(User)
admin.site.register(Article)
admin.site.register(Category)

forms.py

from django import forms

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Row, Layout,Column, ButtonHolder, Submit
from crispy_forms.bootstrap import FormActions

class SignUpForm(forms.Form):

    username = forms.CharField(
        label='Username',
        widget=forms.TextInput(attrs={"class": "form-control"})
    )
    password = forms.CharField(
        label='Password',
        max_length=50,
        widget=forms.PasswordInput(attrs={"class": "form-control"})
    )
    password_confirm = forms.CharField(
        label='Confirm Password',
        max_length=50,
        widget=forms.PasswordInput(attrs={"class": "form-control"}),
    )
    email = forms.EmailField(
        label="Email",
        max_length=50,
        widget=forms.EmailInput(attrs={"class": "form-control"}),
    )
    profile_pic = forms.ImageField(
        widget=forms.ClearableFileInput(attrs={"class": "form-control"})
    )
    date_of_birth = forms.DateField(
        widget=forms.DateInput(attrs={"class": "form-control", "type": "date"})
    )

    helper = FormHelper()
    helper.form_id = 'signup-form'
    helper.layout = Layout(
        Row('username', css_class='mb-2'),
        Row('password', css_class='mb-2'),
        Row('password_confirm', css_class='mb-2'),
        Row('email', css_class='mb-2'),
        Row('profile_pic', css_class='mb-2'),
        Row('date_of_birth', css_class='mb-2'),
        FormActions(
            Submit('signup', 'Sign up', css_class="btn-primary"),
            css_class='mt-3'
        )
    )
class LoginForm(forms.Form):

    username = forms.CharField(
        label='Username',
        widget=forms.TextInput(attrs={"class": "form-control"})
    )
    password = forms.CharField(
        label='Password',
        max_length=50,
        widget=forms.PasswordInput(attrs={"class": "form-control"})
    )
    
    helper = FormHelper()
    helper.form_id = 'login-form'
    helper.layout = Layout(
        Row('username', css_class='mb-2'),
        Row('password', css_class='mb-2'),
        FormActions(
            Submit('login', 'Login', css_class="btn-primary"),
            css_class='mt-3'
        )
    )

1

There are 1 best solutions below

0
On

Adding the following seemed to solve the problem, users created through admin portal now have hashed password stored when viewed through admin portal and can login in through website login page.

from django.contrib.auth.admin import UserAdmin

admin.site.register(User, UserAdmin)