Invalid credentials even putting right credentails django

39 views Asked by At

I have created a sign in form for my user and when I’m trying to log in it says invalid student_ID or password even though I put my credentials properly I’m using postgresql via Railway I’m a beginner

img

This is my forms.py

from django import forms
from django.forms import ModelForm
from .models import StudentInfo

class StudentInfoForm(forms.ModelForm):
    class Meta:
        model = StudentInfo
        fields = ['student_id', 'firstname', 'lastname', 'middlename', 'course','year', 'section', 'password', 'confirm_password',]
        widgets = {
            'password': forms.PasswordInput(),
            'confirm_password': forms.PasswordInput()
        }
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['student_id'].required = True
        self.fields['firstname'].required = True
        self.fields['lastname'].required = True
        self.fields['course'].required = True
        self.fields['section'].required = True
        self.fields['password'].required = True
        self.fields['confirm_password'].required = True

class SignInForm(forms.Form):
    student_id = forms.CharField(label='Student ID', max_length=10)
    password = forms.CharField(label='Password', widget=forms.PasswordInput)

This is my models.py

from django.db import models
from django.contrib.auth.hashers import make_password

# Create your models here.

class StudentInfo(models.Model):
    student_id = models.CharField(max_length=10, unique=True, primary_key=True)
    firstname = models.CharField(max_length=100)
    lastname = models.CharField(max_length=100)
    middlename = models.CharField(max_length=100, blank=True, null=True)
    course = models.CharField(max_length=100)
    year = models.CharField(max_length=1)
    section = models.CharField(max_length=1)
    password = models.CharField(max_length=128, null=True)
    confirm_password = models.CharField(max_length=128, null=True)

    def __str__(self):
        return f"{self.firstname} {self.lastname}"
    
    def save(self, *args, **kwargs):
        self.password = make_password(self.password)
        super(StudentInfo, self).save(*args, **kwargs)

This is my urls.py

from django.urls import path

from . import views

urlpatterns = [
    path("home/", views.home, name="home"),
    path("index/", views.index, name="index"),
    path("signin/", views.signin, name="signin"),
    path("signup/", views.signup, name="signup"),
    path("dashboard/", views.dashboard, name="dashboard")
]

This is my views.py

from django.shortcuts import render,redirect
from .forms import StudentInfoForm, SignInForm
from .models import StudentInfo
from django.contrib.auth.hashers import check_password
from django.contrib.auth import authenticate, login
from django.contrib import messages

# Create your views here.

def home(request):
    return render(request,"signin/home.html")

def index(request):
    return render(request,"signin/index.html")


def signup(request):
    if request.method == "POST":
        form = StudentInfoForm(request.POST)
        if form.is_valid():
            password = form.cleaned_data.get('password')
            confirm_password = form.cleaned_data.get('confirm_password')
            if password != confirm_password:
                # Passwords don't match, render the form again with an error message
                form.add_error('confirm_password', 'Passwords do not match')
                return render(request, 'signin/signup.html', {'form': form})
            else:
                form.save()
                return redirect('signin')
    else:
        form = StudentInfoForm()
    return render(request, 'signin/signup.html', {'form':form})



def signin(request):
    error_message = None  # Define error_message outside the if block

    if request.method == 'POST':
        form = SignInForm(request.POST)
        if form.is_valid():
            student_id = form.cleaned_data.get('student_id')
            password = form.cleaned_data.get('password')
            # Authenticate user
            user = authenticate(request, username=student_id, password=password)
            if user is not None:
                # User is authenticated, create session
                login(request, user)
                return redirect('dashboard')
            else:
                error_message = "Invalid student ID or password."
    else:
        form = SignInForm()
    return render(request, "signin/signin.html", {'form': form, 'error_message': error_message})

def dashboard(request):
    return render(request, 'signin/dashboard.html')

I'm practicing and debugging this for a long period of time and, I still can't find answer.

1

There are 1 answers

4
Pycm On

Problem :-

You import like below.

from django.contrib.auth import authenticate, login

And then you use it as below.

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

#and

login(request, user)

Which are built in methods. This authenticate function doesn't use your password field in your model.(unless you already wrote code for custom authentication backend and didn't post here.)

So, when you try to log in, that user doesn't exist in django built-in auth system.

Answers :-

1) I suggest you to use django built-in auth system. Django already include built-in auth system, which you can customise for your needs.

2) Write a custom authentication backend. It's not very hard to make a custom authentication backend. It's the only way to make this work, if you want to keep using custom password fields in models.

Examples :-

guide 1

guide 2

guide 3