#django #django-rest-framework #django-serializer #drf-queryset
Вопрос:
Я получаю ошибку AttributeError: объект «Ответ» не имеет атрибута «пользователь» для приведенного ниже кода, который я написал
Я пытаюсь получить информацию о пользователе из контекста и создать модель уведомлений. Я получаю вышеуказанную ошибку при возврате инструкции. Я не понимаю, почему я получаю эту ошибку
Модель
class CourseNotification(models.Model): uid = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, unique=True) course = models.ForeignKey('Course.Course', on_delete=models.SET_NULL, null=True) user = models.ManyToManyField('Profile.myUser',null=True) def get_user(self): return [i for i in self.user.all()] def __str__(self): return self.course.course_title
Вид
class CourseNotificationView(ModelViewSet): queryset = CourseNotification.objects.all() serializer_class = CourseNotificationSerializer authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def get_queryset(self): if self.request.user.email is not None: profile = myUser.objects.get(email=self.request.user.email) if profile is not None: notification = CourseNotification.objects.filter(user=profile) return notification else: return Response(data={"User": "Unauthorized User"}, status=HTTP_401_UNAUTHORIZED) def retrieve(self, request, *args, **kwargs): serializer = self.get_serializer(self.get_queryset(), many=True) return Response(data=serializer.data)
Сериализатор
class CourseNotificationSerializer(serializers.ModelSerializer): class Meta: model = CourseNotification fields = '__all__' def create(self, validated_data): users = self.context['request'].user subject = validated_data['course'] if users is None and subject is None or subject == "": raise serializers.ValidationError({"Invalid": "Subject could not be Invalid"}) checkNotification = self.checkNotification(users, subject) if checkNotification is not None and checkNotification.status_code == 200: return checkNotification validate_subject = self.validateSubject(users, subject) if validate_subject.status_code == 200: return validate_subject get_data = CourseNotification.objects.create(course=subject) get_data.user.add(users) get_data.save() return Response(data=get_data, status=HTTP_201_CREATED, content_type="application/json") @staticmethod def checkNotification(users, subject): get_data = CourseNotification.objects.filter(user=users, course=subject) if get_data: for data in get_data: data.user.remove(users) data.save() return Response(data=get_data, status=HTTP_200_OK, content_type="application/json") @staticmethod def validateSubject(users, subject): get_data = CourseNotification.objects.filter(course=subject).exclude(user=users) if get_data: subject = CourseNotification.objects.get(course=subject) subject.user.add(users) subject.save() return Response(data=get_data, status=HTTP_200_OK, content_type="application/json")
Я пытаюсь добавить данные в модель через API. Я столкнулся с проблемой
Комментарии:
1. Происходит ли ошибка из
users = self.context['request'].user
-за этого ? Не могли бы вы, пожалуйста, добавить ошибку, которую вы получаете??2. Привет, @KhalilAlAhmad, я получаю сообщение об ошибке
return checkNotification
илиreturn validate_subject
всякий раз, когда они звонили. данные созданы успешно. когда я пытаюсь вернуть приведенную выше строку, я получаю ошибку