简体   繁体   English

AttributeError:“学生”对象没有属性“ check_password”

[英]AttributeError:'Student' object has no attribute 'check_password'

I user Custom User Model named Student which inherits Django User Model. 我使用名为Student的自定义用户模型,该模型继承了Django用户模型。 I have problem in its logon when I want to use check_password. 当我想使用check_password时,我在登录时遇到问题。 The error is that Student which is a custom user model has not such attribute. 错误是作为自定义用户模型的Student没有这样的属性。

I wanna login students with the registered information by them. 我想用他们注册的信息登录学生。 and the fields to login is identity_no and student_no. 并且要登录的字段是identity_no和student_no。

models.py: 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: views.py:

class StudentLoginSerializer(serializers.ModelSerializer): user = CustomUserSerializerForLogin() class 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

I print(dir(user_obj)) and the output is: 我打印(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']

There is no check_password in fact. 实际上没有check_password。 the question is how to check the entered student_no is correct. 问题是如何检查输入的student_no是否正确。

Since your Student model has a foreign-key relation to user, you should assign the student's user here: 由于您的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
            # ________________________^

        ...

Ref. 参考 how to login a Custom User Model in django rest API framework (it is a previous question of the same user, that's why I know the models hierarchy) 如何在Django Rest API框架中登录自定义用户模型 (这是同一用户的先前问题,这就是为什么我知道模型层次结构的原因)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Builtins.AttributeError:'NoneType'对象没有属性'check_password' - builtins.AttributeError: 'NoneType' object has no attribute 'check_password' 'NoneType'对象没有属性'check_password' - 'NoneType' object has no attribute 'check_password' AttributeError:“ noneType”对象在Django allauth中没有属性“ check_password”错误 - AttributeError: 'NoneType' object has no attribute 'check_password' error in django allauth AttributeError: 'Student' 对象没有属性 '_values' - AttributeError: 'Student' object has no attribute '_values' AttributeError:类型对象“学生”没有属性“gpa” - AttributeError: type object 'Student' has no attribute 'gpa' AttributeError:“学生”object 没有属性“calculateGrade” - AttributeError: 'Student' object has no attribute 'calculateGrade' AttributeError:类型 object 'Student' 没有属性 'name' - AttributeError: type object 'Student' has no attribute 'name' AttributeError: 'User' 对象没有属性 'check_password_correction' - AttributeError: 'User' object has no attribute 'check_password_correction' AttributeError:“ NoneType”对象没有属性“ password” - AttributeError: 'NoneType' object has no attribute 'password' FastAPI AttributeError:“用户”对象没有“密码”属性 - FastAPI AttributeError: 'User' object has no attribute 'password'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM