【问题标题】:AttributeError:'Student' object has no attribute 'check_password'AttributeError:“学生”对象没有属性“check_password”
【发布时间】:2019-07-07 03:53:48
【问题描述】:

我使用名为 Student 的自定义用户模型,它继承了 Django 用户模型。当我想使用 check_password 时,我的登录出现问题。错误是作为自定义用户模型的 Student 没有这样的属性。

我想用他们注册的信息登录学生。登录的字段是identity_no和student_no。

models.py:

class CustomUser(AbstractUser):
    USER_TYPE_CHOICES = ((1, 'student'),
                         (2, 'professor'),)
    username = models.CharField(max_length=50, unique=True)
    user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES, null=True)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=100)
    identity_no = models.PositiveIntegerField(default=0)
    email = models.EmailField(max_length=300,
                              validators=[RegexValidator
                                          (regex="^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.["r"a-zA-Z0-9-.]+$",
                                           message='please enter the correct format')],
                              )
    date_joined = models.DateTimeField('date joined', default=timezone.now)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)


class Student(models.Model):
    user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
    entry_year = models.PositiveIntegerField()
    student_no = models.PositiveIntegerField()

    def get_full_name(self):
        return self.user.first_name + self.user.last_name

    def __unicode__(self):
        return self.get_full_name()

views.py:

类 StudentLoginSerializer(serializers.ModelSerializer): 用户 = CustomUserSerializerForLogin()

    class Meta:
        model = Student
        fields = [
            "user",
            "student_no", ]

    def validate(self, data):  # validated_data
        user_data = data.pop('user', None)
        identity_no = user_data.get('identity_no')
        print("identity_no", identity_no)
        student_no = data.get("student_no")
        user = Student.objects.filter(
            Q(user__identity_no=identity_no) |
            Q(student_no=student_no)
        ).distinct()
        # user = user.exclude(user__identity_no__isnull=True).exclude(user__identity_no__iexact='')
        if user.exists() and user.count() == 1:
            user_obj = user.first()
        else:
            raise ValidationError("This username or student_no is not existed")
        if user_obj:
            if not user_obj.check_password(student_no):  # Return a boolean of whether the raw_password was correct.
                raise ValidationError("Incorrect Credential please try again")
        return user_obj

我打印(dir(user_obj)),输出为:

 ['DoesNotExist', 'MultipleObjectsReturned', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__unicode__', '__weakref__', '_check_column_name_clashes', '_check_field_name_clashes', '_check_fields', '_check_id_field', '_check_index_together', '_check_local_fields', '_check_long_column_names', '_check_m2m_through_same_relationship', '_check_managers', '_check_model', '_check_model_name_db_lookup_clashes', '_check_ordering', '_check_swappable', '_check_unique_together', '_do_insert', '_do_update', '_get_FIELD_display', '_get_next_or_previous_by_FIELD', '_get_next_or_previous_in_order', '_get_pk_val', '_get_unique_checks', '_meta', '_perform_date_checks', '_perform_unique_checks', '_save_parents', '_save_table', '_set_pk_val', '_state', 'check', 'clean', 'clean_fields', 'courserelationstudent_set', 'date_error_message', 'delete', 'entry_year', 'from_db', 'full_clean', 'get_deferred_fields', 'get_full_name', 'id', 'objects', 'pk', 'prepare_database_save', 'refresh_from_db', 'save', 'save_base', 'serializable_value', 'student_no', 'unique_error_message', 'user', 'user_id', 'validate_unique']

实际上没有 check_password。问题是如何检查输入的 student_no 是否正确。

【问题讨论】:

  • 您的Student 是否继承自AbstractBaseUser
  • 你能分享你的Student模型的(部分)吗?
  • 对我来说,您似乎正在尝试访问“check_password”属性。但是,django 的“auth”模块有一个“check_password”方法。也许这是你的错误,但为了更好的诊断,你应该分享你的“学生”模型。
  • 类 CustomUser(AbstractUser): USER_TYPE_CHOICES = ((1, 'student'), (2, 'professor'),) user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES, null=True) identity_no = models.PositiveIntegerField(default=0) email = models.EmailField(max_length=300) class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) entry_year = models.PositiveIntegerField() student_no = models .PositiveIntegerField()

标签: python django django-rest-framework


【解决方案1】:

由于您的Student 模型与用户具有外键关系,您应该在此处分配学生的用户:

class StudentLoginSerializer(serializers.ModelSerializer):
    ...

    def validate(self, data):  # validated_data
        student = Student.objects.filter(
            Q(identity_no=identity_no) |
            Q(student_no=student_no)
        ).distinct()

        if student.exists() and student.count() == 1:
            user_obj = student.first().user
            # ________________________^

        ...

参考。 how to login a Custom User Model in django rest API framework(这是同一个用户的前一个问题,这就是我知道模型层次结构的原因)

【讨论】:

    猜你喜欢
    • 2020-05-04
    • 2013-11-21
    • 2013-01-21
    • 1970-01-01
    • 2012-12-01
    • 2021-04-19
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多