AttributeError: у объекта 'Student' нет атрибута 'check_password' - PullRequest
0 голосов
/ 06 июля 2019

Я пользовательская пользовательская модель пользователя с именем Student, которая наследует Django User Model. У меня проблема при входе в систему, когда я хочу использовать 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): 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

Я печатаю (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']

На самом деле контрольного пароля нет. вопрос в том, как проверить правильность введенного student_no.

1 Ответ

0 голосов
/ 06 июля 2019

Поскольку ваша модель 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. как войти в пользовательскую модель пользователя в рамках django rest API (это предыдущий вопрос того же пользователя, поэтому я знаю иерархию моделей)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...