TypeError: check_password() missing 1 required positional argument: 'encoded'

Я пытаюсь аутентифицировать пользователя, созданного с помощью оболочки python manage.py, пароль выглядит так :- pbkdf2_sha256$390000$------------------------$- . Я использовал пользовательскую модель пользователя (abstractbaseuser) и бэкенд аутентификации по электронной почте, Сейчас я обрабатываю аутентификацию пользователя путем прямого создания пользователя в таблице БД.

settings.py

AUTH_USER_MODEL = 'accounts.Usermanagement'

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'accounts.backends.EmailAuthBackend',
]

backends.py

# from django.contrib.auth.models import User
from django.contrib.auth.hashers import check_password
from django.contrib.auth import get_user_model

Usermanagement = get_user_model()

class EmailAuthBackend:
    def authenticate(self,request,username,password):
        print("Custom authenticate rqst: ",request)
        try:
            user = Usermanagement.objects.get(emailid=username)
            # print(password)
            # print(user.password)
            # print(check_password(password))
            # print(user.check_password(password))
            if user.password == password or user.password == check_password(password): #! PROBLEM
                return user
            return None
            
        except user.DoesNotExist:
            return None
    
    def get_user(self,user_id): 
        try:
            return Usermanagement.objects.get(pk=user_id)
        except Usermanagement.DoesNotExist:
            return None

managers.py

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

class UsermanagementCustomUserManager(BaseUserManager):
    # create_user(username_field, password=None, **other_fields)
    def create_user(self,emailid,roleid,organizationid,firstname, password=None,
                    passwordexpirydate="2022-12-12 12:00:00",createdby=0,modifiedby=0):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        if not emailid:
            raise ValueError('Users must have an email address')

        user = self.model(
            emailid=self.normalize_email(emailid),
            roleid = roleid,
            organizationid=organizationid,
            firstname = firstname,
            password= make_password(password),
            createdby = createdby,
            modifiedby = modifiedby,
        )

views.py

from django.contrib import messages
from django.http import HttpResponse

from django.contrib.auth import get_user_model

# Check
from django.conf import settings
print("auth backend",settings.AUTHENTICATION_BACKENDS)

# Check
# print(get_user_model())

def loginPage(request):
    # POST
    if request.method == 'POST':
        form = AuthenticationForm(request,data=request.POST)

        if form.is_valid(): # Form Valid
            email = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            #Check
            print("EMAIL: ",email)
            print("PASSWORD: ",password)
            # Authentication USER
            user = authenticate(request,username=email,password=password)
            print("Authenticated ",user) # Check
            # check
            print(user)

            if user is not None: # If User found
                login(request,user)
                # messages.info(request, f"You are now logged in as {email}.")
                return redirect ('inquiries')

            else: # If User Not found
                messages.error(request,"User not found")
                return HttpResponse("User not found, not able to login")

        else: # Form InValid
            messages.error(request,"Invalid username or password.")
            return HttpResponse("Form Invalid")
    # GET
    else:
        form = AuthenticationForm()
        context = {"form":form}
        return render(request,"loginpage.html",context=context)

метод check_password() принимает два аргумента (entered_password, current_password) вам нужно передать текущий пароль пользователя с объектом user следующим образом...

from django.contrib.auth.models import check_password
user = Usermanagement.objects.get(emailid=username)

check_password(password, user.password)
Вернуться на верх