Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function does not return http 400 request

class WaitingForParticipationInEventViewSet(viewsets.ModelViewSet):
    queryset = WaitingForParticipationInEvent.objects.all()
    serializer_class = WaitingForParticipationInEventSerializer
    permission_classes = [permissions.IsAuthenticated]

    def perform_create(self, serializer):
        instance = serializer.save()
        if ParticipationInEvents.objects.filter(user=instance.user, event=instance.event).exists():
            print(5551)
            print(ParticipationInEvents.objects.filter(user=instance.user, event=instance.event).exists())
            return Response({"message": "User already in event"}, status=status.HTTP_400_BAD_REQUEST)
        else:
            waiting_serializer = WaitingForParticipationInEventSerializer(data={'url': instance.url, 'id':        instance.id, 'username': instance.username,'first_name': instance.first_name, 'read': instance.read, 'user': instance.user, 'event': instance.event})
            if waiting_serializer.is_valid():
                waiting_serializer.save()
                print(555)
                return Response({"detail": "Допущено: Объект успешно создан в ModelA."}, status=status.HTTP_201_CREATED)
            return Response(waiting_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

There is my model viewset, when I am creating WaitingForParticipationInEvent object I need to check an existence of ParticipationInEvents object with the same user and event, if exists I return bad request, if does not I create the object. Butyour text it does not return bad requеst though print(5551) works. Help pls

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The issue you’re facing seems to be related to the control flow of your perform_create method in your viewset. Specifically, you’re trying to return a response directly from the perform_create method, which is not the intended way to handle such cases in Django REST Framework.

The perform_create method is meant for performing any additional actions after creating an instance, but it’s not directly responsible for returning the HTTP response. Instead, you should raise an exception if the condition is not met, and then let Django REST Framework’s exception handling process return the appropriate HTTP response.

Here’s how you can modify your code to achieve the desired behavior:

from rest_framework.exceptions import ValidationError

class WaitingForParticipationInEventViewSet(ModelViewSet):
    queryset = WaitingForParticipationInEvent.objects.all()
    serializer_class = WaitingForParticipationInEventSerializer
    permission_classes = [permissions.IsAuthenticated]

    def perform_create(self, serializer):
        instance = serializer.save()
        if ParticipationInEvents.objects.filter(user=instance.user, event=instance.event).exists():
            raise ValidationError("User already in event")
        else:
            waiting_serializer = WaitingForParticipationInEventSerializer(
                data={
                    'url': instance.url,
                    'id': instance.id,
                    'username': instance.username,
                    'first_name': instance.first_name,
                    'read': instance.read,
                    'user': instance.user,
                    'event': instance.event
                }
            )
            if waiting_serializer.is_valid():
                waiting_serializer.save()
            else:
                raise ValidationError(waiting_serializer.errors)

In this modified version:

  1. We’re raising a ValidationError exception when the condition is not met, which will be caught by Django REST Framework’s exception handling and converted into an appropriate HTTP response with a status of 400 Bad Request.

  2. If the condition is met and the serializer is valid, we save the instance using the waiting_serializer.

  3. If there are any issues with the serializer’s validity, we raise a ValidationError with the serializer’s errors, which will also be converted into an appropriate HTTP response.

By raising exceptions, you allow Django REST Framework to handle the response generation and error handling in a more standardized way.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading