AttributeError: 'Userdata' object has no attribute' check_password'

Asked 2 years ago, Updated 2 years ago, 411 views

Prerequisites/What you want to achieve

Customized authentication backend to use authenticate using unique model

Problems/Error Messages you are experiencing

You can see that the error is written as if this problem occurred because the check_password is not defined in Userdata.However, I don't know if this error occurs in my model even though check_password is not set in the user on the reference site.Also, I don't know exactly how and how to introduce check_password, so please let me know.

File "C:\Users\username\testapp\content\backends.py", line 11, in authenticate
    if user.check_password(password) and self.user_can_authenticate(user):
AttributeError: 'Userdata' object has no attribute' check_password'

Source Codes Affected

backends.py

 from django.contrib.auth.backends import ModelBackend
from.models import Userdata

class Userbackend (ModelBackend):
  def authenticate(self, request, email=None, password=None, **kwargs):
    try:
      user=Userdata.objects.get(email=email)
    except Userdata.DoesNotExist:
      return None
    else:
      if user.check_password(password) and self.user_can_authenticate(user):
        return user

models.py

#User Registration
class Userdata(models.Model):
  name=models.CharField(verbose_name='username', max_length=15, unique=True)
  email=models.EmailField(verbose_name='user id', max_length=30, unique=True)
  password=models.CharField(verbose_name='password', max_length=15)
  register_date=models.DateTimeField(default=timezone.now)

Tried

Failed to customize authentication backend with reference to:
(https://django.kurodigi.com/customize-auth-backend/)

The reference site models.py was on a different page, so please refer to the site below.
(https://django.kurodigi.com/custamize-user/)

Supplementary information (for example, FW/Tool Version)

directory configuration  testapp /
 ├ content/
 │ ├ backends.py
 │ ├ models.py
 
Python 3.9.5
django 3.2.5

The code for the parts of the reference site models.py and backends.py that appear to be affected was as follows.
backend.py

 from django.contrib.auth.backends import ModelBackend
from.models import User

class EmailAuthBackend (ModelBackend):
    def authenticate(self, request, email=None, password=None, **kwargs):
        try:
            user=User.objects.get(email=email)
        except User.DoseNotExist:
            return None
        else:
            if user.check_password(password) and self.user_can_authenticate(user):
                return user

models.py

 class User (AbstractBaseUser, PermissionsMixin):
    """
    Customized User Class Based on Django Standard User
    """
    username_validator = UnicodeUsernameValidator()
    # Use ASCIIUsernameValidator to allow only half-width alphanumeric characters in python3
    # username_validator = ASCIIUsernameValidator()

    username=models.CharField(
        _('username',
        max_length = 50,
        unique = True,
        # help_text=_('Required.150 characters orfewer.Letters, digits and@/./+/-/_only.',
        help_text='This item is required.Full-width, half-width alphanumeric characters, @ /./+/-/_ must not exceed 50 characters.',
        validators = [username_validator],
        error_messages={
            'unique':_("A user with that username already exists."),
        },
    )
    # first_name=models.CharField(_('first name'), max_length=30, blank=True)
    # last_name = models.CharField(_('last name'), max_length = 150, blank = True)
    email=models.EmailField(
        _('email address',
        help_text='This item is required.Your email address will not be published.',
        blank=False
    )
    is_staff=models.BooleanField(
        _('staff status',
        default=False,
        help_text=_('Designates where the user can log into this admin site.'),
    )
    is_active=models.BooleanField(
        _('active',
        default = True,
        help_text=_(
            'Designates which this user should have been created as active.'
            'Unselect this installed of deleting accounts.'
        ),
    )
date_joined=models.DateTimeField(_('date joined'), default=timezone.now)

    objects = UserManager()

    EMAIL_FIELD = 'email'
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    class Meta:
        verbose_name=_('user')
        verbose_name_plural=_('users')
        # abstract = True
        abstract = False

    def clean (self):
        super().clean()
        self.email=self.__class__.objects.normalize_email(self.email)

    # Comment out the first_name and last_name sections
    # default_full_name(self):
    #     """
    #     Return the first_name plus the last_name, with a space in between.
    #     """
    #     full_name = '%s%s'% (self.first_name, self.last_name )
    #     return full_name.strip()

    # default_short_name(self):
    #     """Return the short name for the user."""
    #     return self.first_name
def email_user(self, subject, message, from_email=None,**kwargs):
        """Send an email to this user."""
        send_mail(subject, message, from_email, [self.email], **kwargs)

python django

2022-09-30 21:59

1 Answers

The final form of models was written in the following way, and it was resolved.

#User Registration
Class UserManager (BaseUserManager):

  use_in_migrations = True#migrations may not be necessary for special operations

 # General User Behavior
  create_user(self, username, email, date, password=None):
    if not username:
      raise ValueError('The given username must be set')
    elif not email:
      raise ValueError('The give email must be set')
    user=self.model(
      name = username,
      email=self.normalize_email(email),
      register_date=date,
    )
    user.set_password(password)
    user.save(using=self._db)
    return user

  # Superuser Operation
  def create_superuser(self, username, email, password):
    user=self.create_user(
      username,
      email,
      password = password
    )
    user.is_admin=True
    user.save(using=self._db)
    return user

classUserdata(AbstractBaseUser, PermissionsMixin):
 # Unique model you want to use
  name=models.CharField(verbose_name='username', max_length=50, unique=True)
  email=models.EmailField(verbose_name='user id', max_length=30, unique=True)
  password=models.CharField(verbose_name='password', max_length=15)
  date_joined=models.DateTimeField (default=timezone.now)
  is_staff=models.BooleanField(default=False)
  is_active=models.BooleanField(default=True)

  # Objects used in Userdata.objects.all() and so on
  objects = UserManager()

  EMAIL_FIELD = 'email' (required for users to check via email when changing passwords)
  USERNAME_FIELD = 'email' 
                For username authentication: USERNAME_FIELD = 'username'
                             For email authentication: USERNAME_FIELD='email'
               )
  Additional items to be asked when REQUIRED_FIELDS=[]#createsuperuser


2022-09-30 21:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.