简体   繁体   中英

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

I user Custom User Model named Student which inherits Django User Model. I have problem in its logon when I want to use check_password. The error is that Student which is a custom user model has not such attribute.

I wanna login students with the registered information by them. and the fields to login is identity_no and 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:

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

 ['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. the question is how to check the entered student_no is correct.

Since your Student model has a foreign-key relation to user, you should assign the student's user here:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM