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

时间:2019-07-06 10:41:54

标签: python django django-rest-framework

我使用名为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是否正确。

1 个答案:

答案 0 :(得分:0)

由于您的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(这是同一用户的先前问题,这就是为什么我知道模型层次结构的原因)